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';
import { NotificationsComponent } from 'src/app/core/notifications/notifications.component';

@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 };

	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);
					NotificationsComponent.success('Image de profil modifiée.');
				}
				this.selectedFiles = undefined;
			}, error => {
				console.log(error);
				NotificationsComponent.error('Une erreur est survenue lors de l\'upload de votre image de profil.');
			});
		}
	}

	onSubmit(): void {
		this.profilEditionService.updateUser(this.model).subscribe(() => {
			NotificationsComponent.success('Modifications enregistrées.');
		}, error => {
			NotificationsComponent.error('L\'adresse mail saisie n\'est pas disponible.');
		});
	}
}
