import {Component, ViewChild} from '@angular/core';
import {ActivatedRoute, Router} from "@angular/router";
import {EmployeeGroup, EmployeePermission} from "../../../shared/model/employee";
import {GroupService} from "../../services/group.service";
import {FormBuilder, FormControl, FormGroup, Validators} from "@angular/forms";
import {PermissionsFieldComponent} from "../../../shared/components/permissions-field/permissions-field.component";
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 {
  @ViewChild('permissionsField') permissionsField: PermissionsFieldComponent

  group: EmployeeGroup | null
  unknownError = false

  private _nameControl: FormControl

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

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

  submit(): void {
    if (this.form.valid && this.permissionsField.valid()) {
      this.subscribe(
        this.groupService.update(this.group.id, this.nameControl.value, this.permissionsField.allEnabledPermissions),
        {
          next: () => this.router.navigate(['/group/list']),
          error: err => {
            this.unknownError = true
            console.log(err)
          }
        }
      )
    }
  }

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

  get form(): FormGroup {
    return this.formBuilder.group({
      name: this.nameControl
    })
  }

  get confirmBoxMessage(): string {
    return `Voulez-vous vraiment supprimer le groupe ${this.group.name}?`
  }

  get nameControl(): FormControl {
    if (this._nameControl) return this._nameControl
    if (this.group) {
      this._nameControl = new FormControl(this.group.name, Validators.compose([Validators.required, Validators.minLength(3)]))
      return this._nameControl
    }
    return null
  }

  get canRemoveGroup(): boolean {
    return this.accountService.hasPermission(EmployeePermission.REMOVE_EMPLOYEE_GROUP)
  }
}
