import './style.scss';

var Status = {
	 NONE      : 0
	,WAITING   : 1
	,UPLOADING : 2
	,UPLOADED  : 3
};

export default new Class({
	Extends: Hedera.Form,
	Template: require('./ui.xml')

	,filesData: []
	,uploadCount: 0
	,isUploading: false

	,activate() {
		this.$.schema.value = 'catalog';
	}

	,addFiles(files) {
		if (!files)
			return;

		for (var i = 0; i < files.length; i++)
			this.addFile(files[i]);
	}

	,addFile(file) {
		var doc = document;
		var li = doc.createElement('div');

		var div = doc.createElement('div');
		div.className = 'thumb';
		li.appendChild(div);

		var thumb = doc.createElement('img');
		thumb.file = file;
		div.appendChild(thumb);

		var reader = new FileReader();
		reader.onload = function(e) {
			thumb.src = e.target.result; 
		};
		reader.readAsDataURL(file);

		var name = doc.createElement('input');
		name.type = 'text';
		name.value = getFileName(file.name);
		li.appendChild(name);

		var statusNode = doc.createElement('div');
		statusNode.className = 'status';
		li.appendChild(statusNode);

		var fileData = {
			li: li,
			file: file,
			name: name,
			statusNode: statusNode
		};

		var button = new Htk.Button({
			tip: 'Remove',
			icon: 'delete'
		});
		button.node.addEventListener('click',
			() => this.onFileRemove(fileData));
		li.appendChild(button.node);

		this.filesData.push(fileData);

		this.$.fileList.appendChild(li);
		this.setImageStatus(fileData, Status.NONE, 'add', _('Pending upload'));
	}

	,async onUploadClick() {
		if (this.isUploading) return;
	
		const uploadQueue = [];
		let hasFiles = false;

		for (const fileData of this.filesData) {
			if (fileData.status !== Status.NONE) continue;
			this.setImageStatus(
				fileData, Status.WAITING, 'cloud_upload', _('Waiting for upload'));
			fileData.name.disabled = true;
			uploadQueue.push(fileData);
			hasFiles = true;
		}

		if (!hasFiles) {
			Htk.Toast.showWarning(_('There are no files to upload'));
			return;
		}

		this.isUploading = true;
		let hasErrors = false;
		
		for (const fileData of uploadQueue) {
			this.setImageStatus(
				fileData, Status.UPLOADING, 'upload', _('Uploading file'));

			const formData = new FormData();
			formData.append('updateMatching', this.$.updateMatching.value);
			formData.append('image', fileData.file);
			formData.append('name', fileData.name.value);
			formData.append('schema', this.$.schema.value);
			formData.append('srv', 'json:image/upload');

			try {
				await this.conn.sendFormData(formData);
				this.setImageStatus(
					fileData, Status.UPLOADED, 'cloud_done', _('Image uploaded'));
			} catch(err) {
				this.setImageStatus(
					fileData, Status.NONE, 'error', err.message);
				fileData.name.disabled = false;
				hasErrors = true;
			}
		}

		this.isUploading = false;

		if (hasErrors)
			Htk.Toast.showError(_('Some errors happened on upload'));
		else
			Htk.Toast.showMessage(_('Upload finished successfully'));
	}

	,setImageStatus(fileData, status, icon, title) {
		fileData.status = status;

		var statusNode = fileData.statusNode;
		Vn.Node.removeChilds(statusNode);
	
		var iconNode = new Htk.Icon({name: icon});
		statusNode.appendChild(iconNode.node);
		statusNode.title = title ? title : '';
	}

	,onFileRemove(fileData) {
		this.$.fileList.removeChild(fileData.li);

		for (var i = 0; i < this.filesData.length; i++)
		if (this.filesData[i] === fileData) {
			this.filesData.splice(i, 1);
			break;
		}
	}

	,onClearClick() {
		this.filesData = [];
		Vn.Node.removeChilds(this.$.fileList);
	}

	,onDropzoneClick() {
		this.$.file.click();
	}

	,onFileChange() {
		this.addFiles(this.$.file.files);
	}

	,onDragEnter() {
		this.$.dropzone.classList.add('dragover');
	}

	,onDragLeave() {
		this.$.dropzone.classList.remove('dragover');
	}

	,onDragOver(event) {
		event.preventDefault();
	}

	,onDragEnd(event) {
		this.$.dropzone.classList.remove('dragover');
		event.dataTransfer.clearData();
	}

	,onDrop(event) {
		event.preventDefault();
		this.addFiles(event.dataTransfer.files);
	}
});

function getFileName(path) {
	var barIndex = path.lastIndexOf('/');
	if (barIndex === -1)
		barIndex = path.lastIndexOf('\\');
	if (barIndex === -1)
		barIndex = 0;

	var dotIndex = path.lastIndexOf('.');
	if (dotIndex === -1)
		dotIndex = 0;

	return path.substr(barIndex, dotIndex);
}
