/** @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 } from '@kangaroo-and-rabbit/kar-cw';
import { UUID } from 'app/back-api';
import { RESTAbort } from 'app/back-api/rest-tools';

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

export class ElementList {
	constructor(
		public value: number,
		public label: string) {
	}
}

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

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

	error: string = '';

	typeId: number = null;
	name: string = '';
	description: string = '';
	coverFile: File;
	uploadFileValue: string = '';
	selectedFiles: FileList;

	seasonsCount: string = null;
	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();


	listType: ElementList[] = [
		{ value: undefined, label: '---' },
	];

	// ---------------  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 seriesService: SeriesService,
		private typeService: TypeService,
		private arianeService: ArianeService,
		private popInService: PopInService,
	) {

	}

	ngOnInit() {
		this.idSeries = this.arianeService.getSeriesId();
		let self = this;
		this.listType = [{ 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.get(this.idSeries)
			.then((response) => {
				// console.log("get response of video : " + JSON.stringify(response, null, 2));
				self.name = response.name;
				self.typeId = response.parentId;
				self.description = response.description;
				self.updateCoverList(response.covers);
				// console.log("covers_list : " + JSON.stringify(self.covers_display, null, 2));
				self.itemIsLoading = false;
			}).catch((response) => {
				self.error = 'Can not get the data';
				self.name = '';
				self.description = '';
				self.coversDisplay = [];
				self.itemIsNotFound = true;
				self.itemIsLoading = false;
			});
		console.log(`get parameter id: ${this.idSeries}`);
		this.seriesService.getSeason(this.idSeries)
			.then((response) => {
				self.seasonsCount = "" + response.length;
			}).catch((response) => {
				self.seasonsCount = '---';
			});
		this.seriesService.getVideo(this.idSeries)
			.then((response) => {
				self.videoCount = "" + response.length;
			}).catch((response) => {
				self.videoCount = '---';
			});
	}

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

	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 = [];
		}
	}

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

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

	onChangeType(value: any): void {
		console.log(`Change requested of type ... ${value}`);
		this.typeId = value;
		if (this.typeId === undefined) {
			this.typeId = null;
		}
	}

	sendValues(): void {
		console.log('send new values....');
		let data = {
			parentId: this.typeId,
			name: this.name,
			description: this.description
		};
		if (this.description === undefined) {
			data.description = null;
		}
		this.seriesService.patch(this.idSeries, 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();
	}

	// 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.seriesService.uploadCover(this.idSeries, 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.seriesService.deleteCover(this.idSeries, 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 Series: ${this.idSeries}`;
		this.deleteItemId = this.idSeries;
		this.popInService.open('popin-delete-confirm');
	}
	removeItemAfterConfirm(_id: number) {
		let self = this;
		this.seriesService.delete(_id)
			.then((response3) => {
				// self.data_ori = tmpp;
				// self.updateNeedSend();
				self.itemIsRemoved = true;
			}).catch((response3) => {
				// self.updateNeedSend();
			});
	}
}
