import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { MatDialog } from '@angular/material/dialog';
import { MatSnackBar } from '@angular/material/snack-bar';
import { ActivatedRoute, Router } from '@angular/router';
import { AuthService } from 'src/app/services/auth.service';
import { TurnoverManagementService } from 'src/app/services/turnover.management.service';
import { TurnoverService } from 'src/app/services/turnover.service';
import { ConfirmDialog } from 'src/app/ui/confirm/confirm.component';

@Component({
  selector: 'page-turnover',
  templateUrl: './turnover.page.html',
  styleUrls: ['./turnover.page.scss']
})
export class PageTurnover implements OnInit {

  id: number;
  turnover: any;
  notfound: boolean = false;
  working: boolean = false;
  success: boolean = false;
  form: FormGroup;
  username: string = "";
  admin: boolean = false;

  constructor(
    private turnoverService: TurnoverService,
    private turnoverManagementService: TurnoverManagementService,
    private authService: AuthService,
    private formBuilder: FormBuilder,
    private router: Router,
    private route: ActivatedRoute,
    private snackBar: MatSnackBar,
    private dialog: MatDialog) { }

  ngOnInit(): void {
    this.form = this.formBuilder.group({
      customer: ['', Validators.required],
      motif: ['', Validators.required],
      price: ['', Validators.required],
      timeInvestment: ['', Validators.nullValidator],
      remark: ['', Validators.nullValidator],
      materialConsumption: ['', Validators.nullValidator],
    });

    this.id = this.route.snapshot.paramMap.get('id') && +this.route.snapshot.paramMap.get('id');
    this.refresh();
  }

  refresh() {
    if (this.id) {
      let request = this.turnoverService.get(this.id);

      this.authService.auth.subscribe({
        next: (auth) => {
          this.username = auth.username;
          this.admin = auth.authorities && auth.authorities.find((role) => role.authority == 'ROLE_ADMIN') != undefined;

          if (this.admin) {
            request = this.turnoverManagementService.get(this.id);
          }

          request.subscribe({
            next: (data) => {
              this.turnover = data;
              this.form.get("customer").setValue(this.turnover.customer);
              this.form.get("motif").setValue(this.turnover.motif);
              this.form.get("price").setValue(this.turnover.price);
              this.form.get("timeInvestment").setValue(this.turnover.timeInvestment);
              this.form.get("remark").setValue(this.turnover.remark);
              this.form.get("materialConsumption").setValue(this.turnover.materialConsumption);

            },
            error: (error) => {
              if (error.status == 404) {
                this.notfound = true;
              }
            }
          })

        },
        error: (error) => {
          this.username = ""
        }
      })


    } else {
      this.turnover = {};
    }
  }

  hasError(controlName: string): boolean {
    return this.form.controls[controlName].errors != null;
  }

  create(): void {
    if (this.working) {
      return;
    }

    this.working = true;

    this.turnover.customer = this.form.get("customer").value;
    this.turnover.motif = this.form.get("motif").value;
    this.turnover.price = this.form.get("price").value;
    this.turnover.timeInvestment = this.form.get("timeInvestment").value;
    this.turnover.remark = this.form.get("remark").value;
    this.turnover.materialConsumption = this.form.get("materialConsumption").value;

    this.turnoverService.create(this.turnover).subscribe({
      next: (data) => {
        this.router.navigateByUrl('/');
      },
      error: (error) => {
        this.working = false;
        if (error.status == 422) {
          let errors = {};
          for (let code of error.error) {
            errors[code.field] = errors[code.field] || {};
            errors[code.field][code.code] = true;
          }

          for (let code in errors) {
            this.form.get(code).setErrors(errors[code]);
          }
        }
      }
    })

  }

  update(): void {
    if (this.working) {
      return;
    }

    this.working = true;
    this.turnover.customer = this.form.get("customer").value;
    this.turnover.motif = this.form.get("motif").value;
    this.turnover.price = this.form.get("price").value;
    this.turnover.timeInvestment = this.form.get("timeInvestment").value;
    this.turnover.remark = this.form.get("remark").value;
    this.turnover.materialConsumption = this.form.get("materialConsumption").value;

    const request = this.admin ? this.turnoverManagementService.update(this.turnover) : this.turnoverService.update(this.turnover);

    request.subscribe({
      next: (data) => {
        this.turnover = data;
        this.working = false;
        this.success = true;
      },
      error: (error) => {
        this.working = false;
        if (error.status == 403) {
          this.snackBar.open("Error");
        }
        if (error.status == 422) {
          let errors = {};
          for (let code of error.error) {
            errors[code.field] = errors[code.field] || {};
            errors[code.field][code.code] = true;
          }

          for (let code in errors) {
            this.form.get(code).setErrors(errors[code]);
          }
        }
      }
    })
  }

  deleteTurnover() {
    const dialogRef = this.dialog.open(ConfirmDialog, {
      data: {
        'label': 'turnover.confirmDelete',
        'args': [this.turnover.username]
      }
    })

    dialogRef.afterClosed().subscribe({
      next: (result) => {
        if (result) {
          this.turnoverManagementService.delete(this.turnover.id).subscribe({
            next: () => {
              this.router.navigateByUrl('/');
            }
          });
        }
      }
    });
  }

}
