import { Component } from '@angular/core';
import { User } from '../core/entities';
import { SigninService } from './signin.service';
import { Router } from '@angular/router';

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

		.submitFormArea {
			line-height: 50px;
		}

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

	constructor(
		private signinService: SigninService,
		private router: Router
	) {}

	onSubmit(): void {
		if (this.confirmPassword && this.confirmPassword === this.model.password) {
			this.signinService.signin(this.model).subscribe(() => {
				this.router.navigate(['/login']);
			}, error => {
				// FIXME: Type the error to get the status.
				switch (error.status) {
				case 409:
					this.setMessage('L\'adresse mail saisie n\'est pas disponible');
					break;
				default:
					this.setMessage('Une erreur est survenue lors de l\'inscription, veuillez réessayer plus tard');
					break;
				}
			});
		} else {
			this.setMessage('Les mots de passe saisis ne correspondent pas');
		}
	}

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

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

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