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

import { AuthService } from '../../services/auth.service';
import { MatchingValidator } from '../../utils/matching.validator';
import { ActivatedRoute, Router } from '@angular/router';

@Component({
  selector: 'app-password-reset',
  templateUrl: './password-reset.component.html',
  styleUrls: ['./password-reset.component.scss']
})
export class PasswordResetComponent implements OnInit {

  form: FormGroup;
  model: any = {};
  public working: boolean;
  public success: boolean;
  public tokenInvalid: boolean = false;

  constructor(
    private formBuilder: FormBuilder,
    private authService: AuthService,
    private router: Router,
    private route: ActivatedRoute) { }

  ngOnInit(): void {
    this.form = this.formBuilder.group({
      password: ['', Validators.required],
      password2: ['', Validators.required]
    }, {
      validator: MatchingValidator('password', 'password2')
    });

    this.route.queryParams.subscribe(params => {
      if (params.token) {
        this.model.token = params.token;
      }
    });

  }

  passwordReset() {
    this.working = true;
    this.authService.passwordReset(this.model).subscribe(response => {
      this.success = true;
    }, (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.form.get(code).setErrors(errors[code]);
        }
      } else {
        this.tokenInvalid = true;
      }
    })
  }

}
