import { Component, OnInit } from '@angular/core';
import {ActivatedRoute, Router} from "@angular/router";
import {LoginService} from "../../service/login.service";
import {MessageService} from "primeng/api";
import {FormControl, FormGroup} from "@angular/forms";
import {checkValidator} from "../../validator/check-password.directive";

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

  show:boolean=false;
  username?:string;
  changeForm!: FormGroup;

  constructor(private route: ActivatedRoute,private loginService: LoginService,private messageService: MessageService,private router:Router) {

  }

  ngOnInit(): void {

    this.changeForm = new FormGroup({
      password: new FormControl(),
      confirmedPassword: new FormControl()
    },{ validators: checkValidator })

    var token = this.route.snapshot.paramMap.get('token');
    if(token != undefined){
      this.loginService.checkToken(token).subscribe(data =>{
        this.show = true;
        this.username = data.username;
        },
        error => {
            this.show = false;
            this.messageService.add({severity: 'error', detail: 'This change password request has expired! Try again!'});
          this.router.navigate(['/login']);
        })
    }
  }
  changePassword(){
    // @ts-ignore
    this.loginService.changePassword(this.username,this.password.value).subscribe(data =>{
      this.router.navigate(['/login']);
      },error => {
        this.messageService.add({severity: 'error', detail: 'Something went wrong...'});
      }
    )
  }

  get password() { return this.changeForm.get('password')!; }
  get confirmedPassword() { return this.changeForm.get('confirmedPassword')!; }


}
