import { Component, OnDestroy, OnInit } from '@angular/core';
import { AbstractControlOptions, FormBuilder, FormGroup, Validators } from '@angular/forms';

import { UserService } from '../../services/user.service';
import { MatchingValidator } from 'src/app/utils/matching.validator';

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

  auth: any;
  working: boolean = false;
  passwordSuccess: boolean = false;
  passwordForm: FormGroup;

  constructor(
    private userService: UserService,
    private formBuilder: FormBuilder) { }

  ngOnInit(): void {
    this.passwordForm = this.formBuilder.group({
      old: ['', Validators.nullValidator],
      password: ['', Validators.nullValidator],
      password2: ['', Validators.nullValidator]
    }, {
      validator: MatchingValidator('password', 'password2')
    } as AbstractControlOptions);
  }

  ngOnDestroy(): void {
  }

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

  setPassword() {
    if (this.working) {
      return;
    }

    this.working = true;
    this.passwordSuccess = false;
    this.userService.setPassword(this.passwordForm.get('old').value, this.passwordForm.get('password').value, this.passwordForm.get('password2').value).subscribe({
      next: () => {
        this.working = false;
        this.passwordSuccess = true;
      },
      error: (error) => {
        this.working = false;
        if (error.status == 409) {
          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.passwordForm.get(code).setErrors(errors[code]);
          }
        }
      }
    })
  }

}
