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

Hedera.Photos = new Class
({
	Extends: Hedera.Form
	,filesData: []
	,uploadCount: 0
	,errors: false
	,uploadQueue: []
	,isUploading: false

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

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

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

	,addFile: function(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 button = new Htk.Button({
			tip: 'Remove',
			icon: 'delete'
		});
		button.on('click', this.onFileRemove, this);
		li.appendChild(button.node);

		var fileData = {
			li: li,
			file: file,
			name: name,
			statusNode: statusNode
		};
		this.filesData.push(fileData);
		button.value = fileData;

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

	,onUploadClick: function() {
		var filesData = this.filesData;
		var count = 0;

		for (var i = 0; i < filesData.length; i++) {
			var fileData = filesData[i];

			if (fileData.status === Status.NONE) {
				this.setImageStatus(
					fileData, Status.WAITING, 'cloud-upload', _('Waiting for upload'));
				fileData.name.disabled = true;
				this.uploadQueue.push(fileData);
				count++;
			}
		}

		if (count === 0)
			Htk.Toast.showWarning(_('There are no files to upload'));
		else
			this.uploadNextFile();
	}

	,uploadNextFile: function() {
		if (this.isUploading)
			return;

		this.isUploading = true;

		var fileData = this.uploadQueue.shift();
		this.setImageStatus(
			fileData, Status.UPLOADING, 'upload', _('Uploading file'));

		var formData = new FormData();
		formData.append('updateMatching', this.$('update-matching').value);
		formData.append('image', fileData.file);
		formData.append('name', fileData.name.value);
		formData.append('schema', this.$('schema').value);
		formData.append('srv', 'json:image/upload');
		this.conn.sendFormData(formData,
			this.onFileUpload.bind(this, fileData));
	}

	,onFileUpload: function(fileData, data, error) {
		this.isUploading = false;

		if (data) {
			this.setImageStatus(
				fileData, Status.UPLOADED, 'ok', _('Image uploaded'));
		} else {
			this.setImageStatus(
				fileData, Status.NONE, 'error', error.message);
			fileData.name.disabled = false;
			this.errors = true;
		}

		if (this.uploadQueue.length === 0) {
			if (this.errors)
				Htk.Toast.showError(_('Some errors happened on upload'));
			else
				Htk.Toast.showMessage(_('Upload finished successfully'));

			this.errors = false;
		} else
			this.uploadNextFile();
	}

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

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

	,onFileRemove: function(button) {
		var fileData = button.value;
		this.$('file-list').removeChild(fileData.li);

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

	,onClearClick: function() {
		this.filesData = [];
		Vn.Node.removeChilds(this.$('file-list'));
	}

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

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

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

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

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

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

	,onDrop: function(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);
}
})();