import { Component, OnInit } from '@angular/core';
import { ProfilEditionService } from './profil-edition.service';
import { HttpEventType, HttpResponse } from '@angular/common/http';
import { User } from '../../core/entities';
import { AuthService } from '../../core/services/auth.service';

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

		.submitFormArea {
			line-height: 50px;
		}

		#profil-image {
			cursor: pointer;
		}

		#resultMsg, #errorMsg {
			max-height: 0;
			overflow: hidden;
			transition: max-height 0.5s ease-out;
			margin: 0;
		}
	`]
})
export class ProfilEditionComponent implements OnInit {
	model: User;
	selectedFiles: FileList;
	currentFileUpload: File;
	progress: { percentage: number } = { percentage: 0 };
	modelError: string;
	result: string;

	constructor(
		private profilEditionService: ProfilEditionService,
		private authService: AuthService
	) {}

	ngOnInit(): void {
		this.model = this.authService.getUser();
	}

	getAvatarUrl(): string {
		return this.model.image
				? `/api/images/loadAvatar/${this.model.image}`
				: './assets/images/default_user.png';
	}

	triggerProfilImageChange(): void {
		document.getElementById('profilImageInput').click();
	}

	uploadImage(event) {
		this.selectedFiles = event.target.files;
		this.progress.percentage = 0;

		this.currentFileUpload = this.selectedFiles.item(0);
		// This prevents error 400 if user doesn't select any file to upload and close the input file.
		if (this.currentFileUpload) {
			this.profilEditionService.uploadAvatarPicture(this.currentFileUpload).subscribe(result => {
				if (result.type === HttpEventType.UploadProgress) {
					this.progress.percentage = Math.round(100 * result.loaded / result.total);
				} else if (result instanceof HttpResponse) {
					console.log('File ' + result.body + ' completely uploaded!');
					this.model.image = result.body as string;
					this.authService.setAuthenticated(this.model);
					this.setMessage('Image de profil modifiée.', false);
				}
				this.selectedFiles = undefined;
			});
		}
	}

	onSubmit(): void {
		this.profilEditionService.updateUser(this.model).subscribe(() => {
			this.setMessage('Modification enregistrée.', false);
		}, error => {
			this.setMessage('L\'adresse mail saisie n\'est pas disponible.', true);
		});
	}

	setMessage(message: string, error: boolean): void {
		this[error ? 'modelError' : 'result'] = message;

		const resultMsgDiv = document.getElementById(error ? 'errorMsg' : 'resultMsg');
		resultMsgDiv.style.maxHeight = '64px';

		setTimeout(() => {
			resultMsgDiv.style.maxHeight = '0px';
			setTimeout(() => {
				this[error ? 'modelError' : 'result'] = undefined;
			}, 550);
		}, 3000);
	}
}
