import {Component, OnDestroy, OnInit, ViewChild} from '@angular/core';
import {FormControl, FormGroup, Validators} from "@angular/forms";
import {PermissionsFieldComponent} from "../../../shared/components/permissions-field/permissions-field.component";
import {EmployeeGroup} from "../../../shared/model/employee";
import {Observable, Subject} from "rxjs";
import {GroupService} from "../../../groups/services/group.service";
import {take, takeUntil} from "rxjs/operators";
import {EmployeeService} from "../../services/employee.service";
import {Router} from "@angular/router";
import {SubscribingComponent} from "../../../shared/components/subscribing.component";

@Component({
  selector: 'cre-add',
  templateUrl: './add.component.html',
  styleUrls: ['./add.component.sass']
})
export class AddComponent extends SubscribingComponent {
  @ViewChild('permissionsField', {static: true}) permissionsField: PermissionsFieldComponent

  form: FormGroup
  idControl: FormControl
  firstNameControl: FormControl
  lastNameControl: FormControl
  passwordControl: FormControl
  groupControl: FormControl
  unknownError = false

  group$: Observable<EmployeeGroup[]> | null

  constructor(
    private employeeService: EmployeeService,
    private groupService: GroupService,
    private router: Router
  ) {
    super()
  }

  ngOnInit(): void {
    this.group$ = this.groupService.all

    this.idControl = new FormControl(null, Validators.compose([Validators.required, Validators.pattern(new RegExp('^[0-9]+$')), Validators.min(0)]))
    this.firstNameControl = new FormControl(null, Validators.required)
    this.lastNameControl = new FormControl(null, Validators.required)
    this.passwordControl = new FormControl(null, Validators.compose([Validators.required, Validators.minLength(8)]))
    this.groupControl = new FormControl(null, Validators.min(0))
    this.form = new FormGroup({
      id: this.idControl,
      firstName: this.firstNameControl,
      lastName: this.lastNameControl,
      password: this.passwordControl,
      group: this.groupControl
    })
  }

  submit() {
    if (this.permissionsField.valid() && this.form.valid) {
      this.subscribe(
        this.employeeService.save(
          parseInt(this.idControl.value),
          this.firstNameControl.value,
          this.lastNameControl.value,
          this.passwordControl.value,
          this.groupControl.value,
          this.permissionsField.allEnabledPermissions
        ),
        {
          next: () => this.router.navigate(['/employee/list']),
          error: err => {
            console.error(err)
            this.unknownError = true
          }
        }
      )
    }
  }
}
