import {Component} from '@angular/core';
import {SubscribingComponent} from "../../../shared/components/subscribing.component";
import {EmployeeService} from "../../services/employee.service";
import {Employee} from "../../../shared/model/employee";
import {ActivatedRoute, Router} from "@angular/router";
import {FormBuilder, FormControl, FormGroup, Validators} from "@angular/forms";

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

  form: FormGroup
  passwordControl = new FormControl(null, Validators.compose([Validators.required, Validators.minLength(8)]))

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

  ngOnInit(): void {
    const employeeId = this.activatedRoute.snapshot.paramMap.get('id')
    this.subscribe(
      this.employeeService.get(parseInt(employeeId)),
      {
        next: employee => this.employee = employee
      }
    )

    this.form = this.formBuilder.group({
      password: this.passwordControl
    })
  }

  submit() {
    if (this.form.valid) {
      this.subscribe(
        this.employeeService.updatePassword(this.employee.id, this.passwordControl.value),
        {
          next: () => this.router.navigate(['/employee/list'])
        }
      )
    }
  }
}
