/** @file
 * @author Edouard DUPIN
 * @copyright 2018, Edouard DUPIN, all right reserved
 * @license PROPRIETARY (see license file)
 */

import { Component, OnInit } from '@angular/core';
import { PopInService, UploadProgress, isNumberFinite } from '@kangaroo-and-rabbit/kar-cw';
import { Season, UUID } from 'app/back-api';
import { RESTAbort } from 'app/back-api/rest-tools';

import { SeasonService, ArianeService, DataService } from 'app/service';

export interface ElementList {
	value: number;
	label: string;
}

@Component({
	selector: 'app-season-edit',
	templateUrl: './season-edit.html',
	styleUrls: ['./season-edit.less']
})

export class SeasonEditScene implements OnInit {
	idSeason: number = -1;
	itemIsRemoved: boolean = false;
	itemIsNotFound: boolean = false;
	itemIsLoading: boolean = true;

	error: string = '';

	numberVal: string = null;
	description: string = '';
	coverFile?: File;
	uploadFileValue: string = '';
	selectedFiles?: FileList;
	videoCount: string = null;


	coversDisplay: Array<any> = [];
	// section tha define the upload value to display in the pop-in of upload
	public upload: UploadProgress = new UploadProgress();
	// ---------------  confirm section  ------------------
	public confirmDeleteComment: string = null;
	public confirmDeleteImageUrl: string = null;
	private deleteCoverId: UUID = null;
	private deleteItemId: number = null;
	cancelHandle: RESTAbort = {};
	deleteConfirmed() {
		if (this.deleteCoverId !== null) {
			this.removeCoverAfterConfirm(this.deleteCoverId);
			this.cleanConfirm();
		}
		if (this.deleteItemId !== null) {
			this.removeItemAfterConfirm(this.deleteItemId);
			this.cleanConfirm();
		}
	}
	cleanConfirm() {
		this.confirmDeleteComment = null;
		this.confirmDeleteImageUrl = null;
		this.deleteCoverId = null;
		this.deleteItemId = null;
	}


	constructor(
		private dataService: DataService,
		private seasonService: SeasonService,
		private arianeService: ArianeService,
		private popInService: PopInService,
	) {

	}

	ngOnInit() {
		this.idSeason = this.arianeService.getSeasonId();
		let self = this;
		this.seasonService.get(this.idSeason)
			.then((response: Season) => {
				console.log(`get response of season : ${JSON.stringify(response, null, 2)}`);
				if (isNumberFinite(response.name)) {
					self.numberVal = response.name;
				}
				self.description = response.description;
				self.updateCoverList(response.covers);
				self.itemIsLoading = false;
			}).catch((response) => {
				self.error = 'Can not get the data';
				self.numberVal = null;
				self.description = '';
				self.coversDisplay = [];
				self.itemIsNotFound = true;
				self.itemIsLoading = false;
			});
		this.seasonService.getVideo(this.idSeason)
			.then((response: any) => {
				self.videoCount = response.length;
			}).catch((response: any) => {
				self.videoCount = '---';
			});
	}

	updateCoverList(covers: any) {
		this.coversDisplay = [];
		if (covers !== undefined && covers !== null) {
			for (let iii = 0; iii < covers.length; iii++) {
				this.coversDisplay.push({
					id: covers[iii],
					url: this.dataService.getThumbnailUrl(covers[iii])
				});
			}
		} else {
			this.coversDisplay = [];
		}
	}
	onNumber(value: any): void {
		this.numberVal = value;
	}

	onDescription(value: any): void {
		this.description = value;
	}

	sendValues(): void {
		console.log('send new values....');
		let data = {
			name: `${this.numberVal}`,
			description: this.description
		};
		if (this.description === undefined) {
			data.description = null;
		}
		this.seasonService.patch(this.idSeason, data);
	}

	// At the drag drop area
	// (drop)="onDropFile($event)"
	onDropFile(event: DragEvent) {
		event.preventDefault();
		// this.uploadFile(event.dataTransfer.files[0]);
	}

	// At the drag drop area
	// (dragover)="onDragOverFile($event)"
	onDragOverFile(event) {
		event.stopPropagation();
		event.preventDefault();
	}

	abortUpload(): void {
		this.cancelHandle.abort();
	}

	// At the file input element
	// (change)="selectFile($event)"
	onChangeCover(value: any): void {
		this.selectedFiles = value.files;
		this.coverFile = this.selectedFiles[0];
		console.log(`select file ${this.coverFile.name}`);
		this.uploadCover(this.coverFile);
	}

	uploadCover(file: File) {
		if (file === undefined) {
			console.log('No file selected!');
			return;
		}
		let self = this;
		// clean upload labels
		this.upload.clear();
		// display the upload pop-in
		this.popInService.open('popin-upload-progress');
		this.seasonService.uploadCover(this.idSeason, file, (count, total) => {
			self.upload.mediaSendSize = count;
			self.upload.mediaSize = total;
		}, this.cancelHandle)
			.then((response: any) => {
				self.upload.result = 'Cover added done';
				// we retrive the whiole media ==> update data ...
				self.updateCoverList(response.covers);
			}).catch((response: any) => {
				// self.error = "Can not get the data";
				console.log('Can not add the cover in the video...');
			});
	}

	removeCover(id: UUID) {
		this.cleanConfirm();
		this.confirmDeleteComment = `Delete the cover ID: ${id}`;
		this.confirmDeleteImageUrl = this.dataService.getThumbnailUrl(id);
		this.deleteCoverId = id;
		this.popInService.open('popin-delete-confirm');
	}
	removeCoverAfterConfirm(id: UUID) {
		console.log(`Request remove cover: ${id}`);
		let self = this;
		this.seasonService.deleteCover(this.idSeason, id)
			.then((response: any) => {
				self.upload.result = 'Cover remove done';
				// we retrive the whiole media ==> update data ...
				self.updateCoverList(response.covers);
			}).catch((response: any) => {
				// self.error = "Can not get the data";
				console.log('Can not remove the cover of the video...');
			});
	}

	removeItem() {
		console.log('Request remove Media...');
		this.cleanConfirm();
		this.confirmDeleteComment = `Delete the Season: ${this.idSeason}`;
		this.deleteItemId = this.idSeason;
		this.popInService.open('popin-delete-confirm');
	}
	removeItemAfterConfirm(id: number) {
		let self = this;
		this.seasonService.delete(id)
			.then((response3) => {
				// self.dataOri = tmpp;
				// self.updateNeedSend();
				self.itemIsRemoved = true;
			}).catch((response3) => {
				// self.updateNeedSend();
			});
	}
}
