import { MatSnackBar } from '@angular/material/snack-bar';
import { DialogService } from './../core/dialog.service';
import { HttpErrorBody } from './../model/httpErrorBody';
import { AddAttackAction, UpdateAttackAction, RemoveAttackAction } from './store/attacks.actions';
import { AttacksFeatureState } from './store/attacks.redurecs';
import { Store } from '@ngrx/store';
import { FormGroup } from '@angular/forms';
import { LoadingService } from 'src/app/core/loading.service';
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
import { AttackFormData } from './model/attack-form-data';
import { finalize } from 'rxjs/operators';
import { Attack } from './model/attack.model';
import { Route, Router } from '@angular/router';
import * as moment from 'moment';

@Injectable({
  providedIn: 'root'
})
export class AttacksService {

  public attackFormData: BehaviorSubject<AttackFormData> = new BehaviorSubject(new AttackFormData());

  constructor(private http: HttpClient, private loadingService: LoadingService, private store: Store<AttacksFeatureState>, private router: Router, private dialogService: DialogService, private snackBar: MatSnackBar) {
    this.getAttackFormData();
  }

  getAttackFormData(){
    this.loadingService.enableLoading();
    this.http.get('/tadis/attacks/form').pipe(
      finalize(() => { this.loadingService.disableLoading(); })
    ).subscribe(
      (formData: AttackFormData) => {
        this.attackFormData.next(formData);
      }
    );
  }

  createAttackRecord(attackForm: FormGroup, onSuccessNavigateTo?: String){
    let formValue = attackForm.value;
    this.loadingService.enableLoading();
    this.http.post('/tadis/attacks', formValue).pipe(
      finalize(() => this.loadingService.disableLoading())
    ).subscribe(
      (attack: Attack) => {
        this.snackBar.open('Záznam úspěšně vytvořen.', 'zavřít', { duration: 2500 });
        if (onSuccessNavigateTo)
          this.router.navigate([onSuccessNavigateTo])
        this.store.dispatch(new AddAttackAction(attack));
      }
    );
  }

  updateAttackRecord(attackForm: FormGroup, onSuccessNavigateTo?: String){
    let formValue = attackForm.value;
    this.loadingService.enableLoading();
    this.http.put('/tadis/attacks/' + formValue.id, formValue).pipe(
      finalize(() => this.loadingService.disableLoading())
    ).subscribe(
      (attack: Attack) => {
        this.snackBar.open('Záznam úspěšně uložen.', 'zavřít', { duration: 2500 });
        if (onSuccessNavigateTo)
          this.router.navigate([onSuccessNavigateTo])
        this.store.dispatch(new UpdateAttackAction(attack));
      }
    );
  }

  deleteAttackRecord(attackId: number, onSuccessNavigateTo?: String){
    this.dialogService.confirm('Opravdu smazat?', 'Opravdu si přejete smazat záznam o útoku #'+attackId+" ?").subscribe(result => {
      if (result){
        this.loadingService.enableLoading();
        this.http.delete('/tadis/attacks/' + attackId).pipe(
          finalize(() => this.loadingService.disableLoading())
        ).subscribe(
          success => {
            this.snackBar.open('Záznam úspěšně smazán.', 'zavřít', { duration: 2500 });
            if (onSuccessNavigateTo)
              this.router.navigate([onSuccessNavigateTo])
            this.store.dispatch(new RemoveAttackAction(attackId))
          }
        );
      }
    });
  }

  exportAttacks(ids: number[]){
    this.loadingService.enableLoading();
    this.http.post('/tadis/attacks/export', ids, { responseType: 'blob' }).pipe(
      finalize(() => this.loadingService.disableLoading())
    ).subscribe(
      (blob: Blob) => {
        var downloadURL = window.URL.createObjectURL(blob);
        var link = document.createElement('a');
        link.href = downloadURL;
        let now: Date = new Date();
        link.download = 'útoky_' + moment().locale('cs').format('L') + '.xlsx';
        link.click();
      }
    );
  }
  
}
