import "blueimp-file-upload/js/vendor/jquery.ui.widget.js";
import "blueimp-file-upload/js/jquery.iframe-transport.js";
import "blueimp-file-upload/js/jquery.fileupload.js";
//import "blueimp-file-upload/js/jquery.fileupload-image.js";

export default class Upload {

	constructor(oSpot) {
		this.spot = oSpot;
	}

	pageInit(asHash) {
		let asProject = this.spot.vars(['projects', this.spot.vars('default_project_codename')]);
		this.spot.tmp('status-box', $('#status'));
		if(asProject.editable) {
			$('#fileupload')
				.attr('data-url', this.spot.getActionLink('upload'))
				.fileupload({
					dataType: 'json',
					formData: {t: this.spot.consts.timezone},
					acceptFileTypes: /(\.|\/)(gif|jpe?g|png|mov)$/i,
					done: (e, asData) => {
						$.each(asData.result.files, (iKey, oFile) => {
							let bError = ('error' in oFile);

							//Feedback
							this.addStatus(bError?oFile.error:(this.spot.lang('upload_success', [oFile.name])));

							//Comments
							if(!bError) this.addCommentBox(oFile.id, oFile.thumbnail);
						});
					},
					progressall: (e, data) => {
						let progress = parseInt(data.loaded / data.total * 100, 10);
						$('#progress .bar').css('width', progress+'%');
					}
				});
		}
		else this.addStatus(this.spot.lang('upload_mode_archived', [asProject.name]), true);
	}

	addCommentBox(iMediaId, sThumbnailPath) {
		$('#comments').append($('<div>', {'class':'comment'})
			.append($('<img>', {'class':'thumb', 'src':sThumbnailPath}))
			.append($('<form>')
				.append($('<input>', {'class':'content', 'name':'content', 'type':'text'}))
				.append($('<input>', {'class':'id', 'name':'id', 'type':'hidden', 'value':iMediaId}))
				.append($('<button>', {'class':'save', 'type':'button'})
					.on('click', (oEvent) => {
						var $Form = $(oEvent.currentTarget).parent();
						this.spot.get(
							'add_comment',
							(asData) => {
								this.addStatus(this.spot.lang('media_comment_update', asData.filename));
							},
							{
								id: $Form.find('.id').val(), 
								content: $Form.find('.content').val()
							},
							(sMsgId) => {
								this.addStatus(this.spot.lang(sMsgId));
							}
						);
					})
					.text(this.spot.lang('save'))
				)
			)
		)
	}

	addStatus(sMsg, bClear) {
		bClear = bClear || false;
		if(bClear) this.spot.tmp('status-box').empty();
	
		this.spot.tmp('status-box').append($('<p>').text(sMsg));
	}
}