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

import { Component, OnInit } from '@angular/core';

import { DataService, TypeService, SeriesService, MediaService, ArianeService } from 'app/service';
import { PopInService, UploadProgress } from '@kangaroo-and-rabbit/kar-cw';
import { Media, Season, Series, UUID } from 'app/back-api';
import { RESTAbort } from 'app/back-api/rest-tools';

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


class DataToSend {
	name: string = '';
	description: string = '';
	episode?: number;
	seriesId?: number;
	seasonId?: number;
	dataId?: UUID;
	time?: number;
	typeId?: number;
	covers: number[] = [];
	generatedName: string = '';
}

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

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

	error: string = '';

	data: DataToSend = new DataToSend();
	dataOri: DataToSend = new DataToSend();
	coverFile: File;
	uploadFileValue: string = '';
	selectedFiles: FileList;
	needSend: boolean = false;


	// section tha define the upload value to display in the pop-in of upload
	upload: UploadProgress = new UploadProgress();
	// ---------------  confirm section  ------------------
	public confirmDeleteComment: string = null;
	public confirmDeleteImageUrl: string = null;
	private deleteCoverId: UUID = null;
	private deleteMediaId: number = null;
	deleteConfirmed() {
		if (this.deleteCoverId !== null) {
			this.removeCoverAfterConfirm(this.deleteCoverId);
			this.cleanConfirm();
		}
		if (this.deleteMediaId !== null) {
			this.removeItemAfterConfirm(this.deleteMediaId);
			this.cleanConfirm();
		}
	}
	cleanConfirm() {
		this.confirmDeleteComment = null;
		this.confirmDeleteImageUrl = null;
		this.deleteCoverId = null;
		this.deleteMediaId = null;
	}

	coversDisplay: Array<any> = [];

	listType: ElementList[] = [
		{ value: undefined, label: '---' },
	];
	listUniverse: ElementList[] = [
		{ value: undefined, label: '---' },
		{ value: null, label: '---' },
	];
	listSeries: ElementList[] = [
		{ value: undefined, label: '---' },
	];
	listSeason: ElementList[] = [
		{ value: undefined, label: '---' },
	];
	cancelHandle: RESTAbort = {};
	constructor(
		private dataService: DataService,
		private MediaService: MediaService,
		private seriesService: SeriesService,
		private typeService: TypeService,
		private arianeService: ArianeService,
		private popInService: PopInService,
	) {

	}

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

	updateNeedSend(): boolean {
		this.needSend = false;
		if (this.data.name !== this.dataOri.name) {
			this.needSend = true;
		}
		if (this.data.description !== this.dataOri.description) {
			this.needSend = true;
		}
		if (this.data.episode !== this.dataOri.episode) {
			this.needSend = true;
		}
		if (this.data.time !== this.dataOri.time) {
			this.needSend = true;
		}
		if (this.data.typeId !== this.dataOri.typeId) {
			this.needSend = true;
		}
		if (this.data.seriesId !== this.dataOri.seriesId) {
			this.needSend = true;
		}
		if (this.data.seasonId !== this.dataOri.seasonId) {
			this.needSend = true;
		}
		return this.needSend;
	}

	updateCoverList(covers: any) {
		this.coversDisplay = [];
		this.data.covers = [];
		if (covers !== undefined && covers !== null) {
			for (let iii = 0; iii < covers.length; iii++) {
				this.data.covers.push(covers[iii]);
				this.coversDisplay.push({
					id: covers[iii],
					url: this.dataService.getThumbnailUrl(covers[iii])
				});
			}
		} else {
			this.coversDisplay = [];
		}
	}
	ngOnInit() {
		this.idVideo = this.arianeService.getVideoId();
		let self = this;
		this.listType = [{ value: null, label: '---' }];
		this.listUniverse = [{ value: null, label: '---' }];
		this.listSeries = [{ value: null, label: '---' }];
		this.listSeason = [{ value: null, label: '---' }];
		this.typeService.gets()
			.then((response2) => {
				for (let iii = 0; iii < response2.length; iii++) {
					self.listType.push({ value: response2[iii].id, label: response2[iii].name });
				}
			}).catch((response2) => {
				console.log(`get response22 : ${JSON.stringify(response2, null, 2)}`);
			});
		// this.seriesService.getOrder()
		this.seriesService.gets()
			.then((response3) => {
				for (let iii = 0; iii < response3.length; iii++) {
					self.listSeries.push({ value: response3[iii].id, label: response3[iii].name });
					console.log(`[${self.data.dataId}] Get series: ${response3[iii].id}, label:${response3[iii].name}`);
				}
			}).catch((response3) => {
				console.log(`get response3 : ${JSON.stringify(response3, null, 2)}`);
			});
		this.MediaService.get(this.idVideo)
			.then((response: Media) => {
				console.log(`get response of video : ${JSON.stringify(response, null, 2)}`);
				self.data.name = response.name;
				self.data.description = response.description;
				self.data.episode = response.episode;
				self.data.dataId = response.dataId;
				self.data.time = response.time;
				self.data.generatedName = "????????? TODO ????????? "; // response.generatedName;
				self.onChangeType(response.typeId);
				self.onChangeSeries(response.seriesId);
				self.data.seasonId = response.seasonId;
				if (self.data.seasonId === undefined) {
					self.data.seasonId = null;
				}
				self.dataOri = { ...self.data };
				self.updateCoverList(response.covers);
				self.updateNeedSend();
				console.log(`coversList : ${JSON.stringify(self.coversDisplay, null, 2)}`);
				self.itemIsLoading = false;
			}).catch((response) => {
				self.error = 'Can not get the data';
				self.data = new DataToSend();
				self.coversDisplay = [];
				self.dataOri = { ...self.data };
				self.updateNeedSend();
				self.itemIsNotFound = true;
				self.itemIsLoading = false;
			});
	}

	onChangeType(value: any): void {
		console.log(`Change requested of type ... ${value}`);
		this.data.typeId = value;
		if (this.data.typeId === undefined) {
			this.data.typeId = null;
		}
		this.data.seriesId = null;
		this.data.seasonId = null;
		this.listSeries = [{ value: undefined, label: '---' }];
		this.listSeason = [{ value: undefined, label: '---' }];
		let self = this;
		this.updateNeedSend();
		if (this.data.typeId !== undefined) {
			self.seriesService.getSeriesWithType(this.data.typeId)
				.then((response2: Series[]) => {
					for (let iii = 0; iii < response2.length; iii++) {
						self.listSeries.push({ value: response2[iii].id, label: response2[iii].name });
					}
				}).catch((response2) => {
					console.log(`get response22 : ${JSON.stringify(response2, null, 2)}`);
				});
		}
	}

	onChangeSeries(value: any): void {
		this.data.seriesId = value;
		if (this.data.seriesId === undefined) {
			this.data.seriesId = null;
		}
		this.data.seasonId = null;
		this.listSeason = [{ value: undefined, label: '---' }];
		let self = this;
		if (this.data.seriesId !== undefined) {
			self.seriesService.getSeason(this.data.seriesId)
				.then((response3: Season[]) => {
					for (let iii = 0; iii < response3.length; iii++) {
						self.listSeason.push({ value: response3[iii].id, label: `season ${response3[iii].name}` });
					}
				}).catch((response3) => {
					console.log(`get response22 : ${JSON.stringify(response3, null, 2)}`);
				});
		}
		this.updateNeedSend();
	}
	onChangeSeason(value: any): void {
		this.data.seasonId = value;
		this.updateNeedSend();
	}

	onName(value: any): void {
		this.data.name = value;
		this.updateNeedSend();
	}

	onDescription(value: any): void {
		if (value.length === 0) {
			this.data.description = null;
		} else {
			this.data.description = value;
		}
		this.updateNeedSend();
	}
	onDate(value: any): void {
		if (value.value.length > 4) {
			value.value = this.data.time;
		} else {
			this.data.time = value.value;
		}
		if (this.data.time < 10) {
			this.data.time = null;
		}
		this.updateNeedSend();
	}

	onEpisode(value: any): void {
		if (value.value.length > 4) {
			value.value = this.data.episode;
		} else {
			this.data.episode = parseInt(value.value, 10);
		}
		this.updateNeedSend();
	}

	sendValues(): void {
		console.log('send new values....');
		let data: any = {};
		if (this.data.name !== this.dataOri.name) {
			data.name = this.data.name;
		}
		if (this.data.description !== this.dataOri.description) {
			if (this.data.description === undefined) {
				data.description = null;
			} else {
				data.description = this.data.description;
			}
		}
		if (this.data.episode !== this.dataOri.episode) {
			data.episode = this.data.episode;
		}
		if (this.data.time !== this.dataOri.time) {
			data.time = this.data.time;
		}
		if (this.data.typeId !== this.dataOri.typeId) {
			if (this.data.typeId === undefined) {
				data.typeId = null;
			} else {
				data.typeId = this.data.typeId;
			}
		}
		if (this.data.seriesId !== this.dataOri.seriesId) {
			if (this.data.seriesId === undefined) {
				data.seriesId = null;
			} else {
				data.seriesId = this.data.seriesId;
			}
		}
		if (this.data.seasonId !== this.dataOri.seasonId) {
			if (this.data.seasonId === undefined) {
				data.seasonId = null;
			} else {
				data.seasonId = this.data.seasonId;
			}
		}
		const tmpp = { ...this.data };
		let self = this;
		this.MediaService.patch(this.idVideo, data)
			.then((response3) => {
				self.dataOri = tmpp;
				self.updateNeedSend();
			}).catch((response3) => {
				console.log(`get response22 : ${JSON.stringify(response3, null, 2)}`);
				self.updateNeedSend();
			});
	}

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

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

	// 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);
		this.updateNeedSend();
	}

	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.MediaService.uploadCover(this.idVideo, file, (count, total) => {
			self.upload.mediaSendSize = count;
			self.upload.mediaSize = total;
		}, this.cancelHandle)
			.then((response: any) => {
				console.log(`get response of cover : ${JSON.stringify(response, null, 2)}`);
				self.upload.result = 'Cover added done';
				// we retrieve the while 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...');
				self.upload.error = `Error in the upload of the cover...${JSON.stringify(response, null, 2)}`;
			});
	}

	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.MediaService.deleteCover(this.idVideo, id)
			.then((response: any) => {
				console.log(`get response of remove cover : ${JSON.stringify(response, null, 2)}`);
				self.upload.result = 'Cover remove done';
				// we retrieve the while 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...');
				self.upload.error = `Error in the upload of the cover...${JSON.stringify(response, null, 2)}`;
			});
	}
	removeItem() {
		console.log('Request remove Media...');
		this.cleanConfirm();
		this.confirmDeleteComment = `Delete the Media: ${this.idVideo}`;
		this.deleteMediaId = this.idVideo;
		this.popInService.open('popin-delete-confirm');
	}
	removeItemAfterConfirm(id: number) {
		let self = this;
		this.MediaService.delete(id)
			.then((response3) => {
				// self.dataOri = tmpp;
				// self.updateNeedSend();
				self.itemIsRemoved = true;
			}).catch((response3) => {
				// self.updateNeedSend();
			});
	}

	eventPopUpSeason(event: string): void {
		console.log(`GET event: ${event}`);
		this.popInService.close('popin-new-season');
	}
	eventPopUpSeries(event: string): void {
		console.log(`GET event: ${event}`);
		this.popInService.close('popin-new-series');
	}
	eventPopUpType(event: string): void {
		console.log(`GET event: ${event}`);
		this.popInService.close('popin-new-type');
	}

	newSeason(): void {
		console.log('Request new Season...');
		this.popInService.open('popin-new-season');
	}
	newSeries(): void {
		console.log('Request new Series...');
		this.popInService.open('popin-new-series');
	}
	newType(): void {
		console.log('Request new Type...');
		this.popInService.open('popin-create-type');
	}
}


