import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators, ValidatorFn, ValidationErrors, AbstractControl } from '@angular/forms';
import { Router } from '@angular/router';
import { BackendService } from '../../../../services/backend/backend.service';
import { ToastrService } from 'ngx-toastr';
const shajs = require('sha.js');

@Component({
	selector: 'app-account',
	templateUrl: './account.component.html',
	styleUrls: ['./account.component.css']
})
export class AccountComponent implements OnInit {
	passwdFG:FormGroup;
	submitted:boolean=false;
	minPw:number = 8;
	maxPw:number = 24;
	hash_new:string = '';
	hash_old:string = '';
	isDisabled = false;
	timeLeft:number = 0;
	buttonText:string = "Mise à jour";
	interval:any;

	constructor(private fb:FormBuilder,
				private bs:BackendService,
				private router:Router,
				private toast:ToastrService) { }

	ngOnInit(): void {
		this.passwdFG=this.fb.group({
			old_passwd:["", Validators.required],
			new_passwd:["", [
				Validators.required,
				Validators.pattern('(?=\\D*\\d)(?=[^a-z])(?=[^A-Z]*[A-Z]).{' + this.minPw + ',' + this.maxPw + '}')
			]],
			confirmation:["", [
				Validators.required,
				Validators.pattern('(?=\\D*\\d)(?=[^a-z])(?=[^A-Z]*[A-Z]).{' + this.minPw + ',' + this.maxPw + '}'),
				passwordMatchValidator
			]],
		});
	}

	setTimeoutDisabledButton(timeout:number): void {
		this.timeLeft = timeout;
		this.isDisabled = true;
		this.buttonText = "Mise à jour" + " ... (" + this.timeLeft + ")";
		this.interval = setInterval(() => {
			if(this.timeLeft > 0) {
				this.timeLeft--;
				this.buttonText = "Mise à jour" + " ... (" + this.timeLeft + ")";
			} else {
				this.isDisabled = false;
				this.buttonText = "mise à jour";
				clearInterval(this.interval);
			}
		},1000)
	}

	onUpdate(): void {
		if(this.passwdFG.invalid) {
			return;
		}
		this.hash_new = shajs('sha256').update(this.passwdFG.get('new_passwd').value).digest('hex');
		this.hash_old = shajs('sha256').update(this.passwdFG.get('old_passwd').value).digest('hex');
		const data = {'old':this.hash_old, 'new':this.hash_new};
		this.setTimeoutDisabledButton(3);
		this.bs.updatePasswd(data).subscribe(
			data => {
				this.toast.success("Mise à jour réussie");
			}, err => {
				if(err.status == 401) {
					this.router.navigateByUrl("/login");
				} else {
					this.toast.error(err.error.description);
				}
			}
		);
	}
}

export const passwordMatchValidator: ValidatorFn = (fg: AbstractControl): ValidationErrors | null => {
	let pt = fg.parent as FormGroup;
	if(!pt) return null;
	return pt.get('new_passwd')?.value === pt.get('confirmation')?.value ? null : { 'mismatch' : true };
}
