import {Component} from '@angular/core';
import {PermissionsFieldComponent} from "../../../shared/components/permissions-field/permissions-field.component";
import {FormBuilder, FormControl, FormGroup, Validators} from "@angular/forms";
import {EmployeeService} from "../../services/employee.service";
import {GroupService} from "../../../groups/services/group.service";
import {ActivatedRoute, Router} from "@angular/router";
import {Observable} from "rxjs";
import {Employee, EmployeeGroup, EmployeePermission} from "../../../shared/model/employee";
import {AccountService} from "../../../accounts/services/account.service";
import {SubscribingComponent} from "../../../shared/components/subscribing.component";

@Component({
  selector: 'cre-edit',
  templateUrl: './edit.component.html',
  styleUrls: ['./edit.component.sass']
})
export class EditComponent extends SubscribingComponent {
  employee: Employee | null
  unknownError = false

  group$: Observable<EmployeeGroup[]> | null

  private _idControl: FormControl
  private _firstNameControl: FormControl
  private _lastNameControl: FormControl
  private _groupControl: FormControl

  constructor(
    private accountService: AccountService,
    private employeeService: EmployeeService,
    private groupService: GroupService,
    private activatedRoute: ActivatedRoute,
    private router: Router,
    private formBuilder: FormBuilder
  ) {
    super()
  }

  ngOnInit(): void {
    const employeeId = this.activatedRoute.snapshot.paramMap.get("id")
    this.subscribe(
      this.employeeService.get(parseInt(employeeId)),
      {
        next: employee => this.employee = employee,
        error: err => {
          if (err.status === 404) {
            this.router.navigate(['/employee/list'])
          } else {
            this.unknownError = true
          }
        }
      },
      1
    )

    this.group$ = this.groupService.all
  }

  submit(permissionsField: PermissionsFieldComponent) {
    if (permissionsField.valid() && this.form.valid) {
      this.subscribe(
        this.employeeService.update(
          parseInt(this.idControl.value),
          this.firstNameControl.value,
          this.lastNameControl.value,
          permissionsField.allEnabledPermissions
        ),
        {
          next: () => {
            const group = parseInt(this._groupControl.value)
            if (!isNaN(group)) {
              this.subscribe(
                this.groupService.addEmployeeToGroup(group, this.employee),
                {
                  next: () => this.router.navigate(['/employee/list']),
                  error: err => {
                    console.error(err)
                    this.unknownError = true
                  }
                }
              )
            } else {
              if (this.employee.group) {
                this.subscribe(
                  this.groupService.removeEmployeeFromGroup(this.employee),
                  {
                    next: () => this.router.navigate(['/employee/list']),
                    error: err => {
                      console.error(err)
                      this.unknownError = true
                    }
                  }
                )
              } else {
                this.router.navigate(['/employee/list'])
              }
            }
          },
          error: err => {
            console.error(err)
            this.unknownError = true
          }
        }
      )
    }
  }

  delete() {
    this.subscribe(
      this.employeeService.delete(this.employee.id),
      {
        next: () => this.router.navigate(['/employee/list']),
        error: err => {
          this.unknownError = true
          console.error(err)
        }
      }
    )
  }

  get form(): FormGroup {
    return this.formBuilder.group({
      id: this._idControl,
      firstName: this._firstNameControl,
      lastName: this._lastNameControl,
      group: this._groupControl
    })
  }

  get idControl(): FormControl {
    this._idControl = this.lazyControl(this._idControl, () => new FormControl(this.employee.id, Validators.compose([Validators.required, Validators.pattern(new RegExp('^[0-9]+$')), Validators.min(0)])))
    return this._idControl
  }

  get firstNameControl(): FormControl {
    this._firstNameControl = this.lazyControl(this._firstNameControl, () => new FormControl(this.employee.firstName, Validators.required))
    return this._firstNameControl
  }

  get lastNameControl(): FormControl {
    this._lastNameControl = this.lazyControl(this._lastNameControl, () => new FormControl(this.employee.lastName, Validators.required))
    return this._lastNameControl
  }

  get groupControl(): FormControl {
    this._groupControl = this.lazyControl(this._groupControl, () => new FormControl(this.employee.group?.id))
    return this._groupControl
  }

  private lazyControl(control: FormControl, provider: () => FormControl): FormControl {
    if (control) return control
    if (this.employee) {
      return provider()
    }
    return null
  }

  get canRemoveEmployee(): boolean {
    return this.accountService.hasPermission(EmployeePermission.REMOVE_EMPLOYEE)
  }
}
