import { Component } from '@angular/core';
import { PasswordWrapper } from '../../core/entities';
import { ChangePasswordService } from './change-password.service';
import { RouteReuseStrategy, Router } from '@angular/router';

@Component({
	selector: 'app-change-password',
	templateUrl: './change-password.component.html',
	styles: [`
		#form.card-body {
			padding-bottom: 10px;
		}

		.submitFormArea {
			line-height: 50px;
		}

		#errorMsg {
			max-height: 0;
			overflow: hidden;
			transition: max-height 0.5s ease-out;
			margin: 0;
		}
	`]
})
export class ChangePasswordComponent {
	model: PasswordWrapper = new PasswordWrapper('', '', '');
	error: string;

	constructor(
		private router: Router,
		private changePasswordService: ChangePasswordService
	) {}

	onSubmit(): void {
		if (this.model.newPassword !== this.model.confirmPassword) {
			this.setMessage('Les mots de passe saisis ne correspondent pas.');
		} else {
			this.changePasswordService.changePassword(this.model).subscribe(() => {
				this.router.navigate(['/accountSettings']);
			}, error => {
				this.setMessage('Le mot de passe saisi ne correspond pas au votre.');
			});
		}
	}

	setMessage(message: string): void {
		this.error = message;

		const resultMsgDiv = document.getElementById('errorMsg');
		resultMsgDiv.style.maxHeight = '64px';

		setTimeout(() => {
			resultMsgDiv.style.maxHeight = '0px';
			setTimeout(() => {
				this.error = undefined;
			}, 550);
		}, 3000);
	}
}
