/* global DropzoneUtil  */

/**
 * Static object for managing the Dropzone 'File History' dialog.
 * @global
 */

/** @TODO: responseFlashRedirect reloads assets twice. This is a workaround fix. */
if (typeof DropzoneHistoryUtil === 'undefined') {
    var DropzoneHistoryUtil
}
DropzoneHistoryUtil = {};

/**
 * Generate and render on-screen a 'File History' dialog for a specified dropzone.
 * @see DropzoneUtil.addDropzone
 * @param {jQuery}   $histBtn    Button which launched this dialog
 * @param {Dropzone} dz          The dropzone this button is bound to.
 * @param {object}   historyData History data for the Dropzone's FileRepo. See addDropzone.
 */
DropzoneHistoryUtil.renderHistoryDialog = function($histBtn, dz, historyData) {

	/* Create the modal window and populate its HTML */

	var index = createModal($histBtn);
	var $modal = $('.ops_page_modal_instance[id=' + index + ']');

	var selectedVer = dz.custom.reassignedVersion;

	var html = DropzoneHistoryUtil._generateDialogHTML(historyData, selectedVer);

	$modal
		.find('.ops_page_modal_content')
		.html(html);

	/* Create Preview Dropzone */

	var previewDz = new Dropzone('#fs-history-dropzone', {
		"addRemoveLinks": false,
		"url": '#',
		"clickable": false,
		"dictDefaultMessage": 'No files to show.',
		"autoProcessQueue": false, // Prevent files from being uploaded until submit click.
		"uploadMultiple": true,
		"parallelUploads": 100,
		"maxFiles": 100
	});

	/* Bind version management event handlers */

	var $rollbackBtn = $('#fs-history-submit');
	var $versionSelect = $('#fs-history-versions');

	// 'Rollback' submit confirmation
	$rollbackBtn.click(function() {
		var verId = DropzoneHistoryUtil._getSelectedVersion($versionSelect, historyData);
		if (verId !== null){
			dz.custom.reassignedVersion = verId;
			// Make a deep copy of an array of the files array
			var files = JSON.parse(JSON.stringify(historyData[verId].files));
			DropzoneUtil._setMockFiles(dz, files);
			closeModal(index, true);
		}
	});

	// Past version selection -> update information on screen
	$versionSelect.change(function(){
		var verId = DropzoneHistoryUtil._getSelectedVersion($versionSelect, historyData);

		if (verId !== null) {
			DropzoneHistoryUtil._populateWithVersion($rollbackBtn, previewDz, index, verId, historyData);
		} else {
			// Failed to validate - Pass with no args to reset the fields and disable rollback.
			// noinspection JSCheckFunctionSignatures
			DropzoneHistoryUtil._populateWithVersion($rollbackBtn, previewDz, index);
		}
	});

	/* Re-populate if necessary */

	if (selectedVer) {
		DropzoneHistoryUtil._populateWithVersion($rollbackBtn, previewDz, index, selectedVer, historyData);
	}

	// Set the modal's positioning now that everything has been populated.
	positionModal(index);

};

DropzoneHistoryUtil._getSelectedVersion = function($versionSelect, historyData) {
	var $selectedVerId = $versionSelect.find('option:selected');
	// Ensure they've only selected 1 version.
	if ($selectedVerId.length === 1) {
		var verId = $selectedVerId.data('versionId');
		if (historyData.hasOwnProperty(verId)) {
			return verId;
		}
	}
	return null;
};

/**
 * Generate the HTML to be inserted into the dialog window. This will only be called
 * once when the window is initially generated.
 *
 * historyData Structure: { <versionID>: {
 *    'files': see `mockFiles` above
 *    'details': {verDate:<string eg '22-Jun-2018 11:12'},  userName:<string> }
 * }
 *
 * @param {object}    historyData
 * @param {Dropzone}  dz
 * @returns {selectedVer: *, html: string}
 * @private
 */
DropzoneHistoryUtil._generateDialogHTML = function(historyData, selectedVer) {

	var optionsHtml = '';

	for (let verId in historyData) {
		var selectedOrEmpty = '';

		// == comparison is deliberate here.
		if (selectedVer == verId) {
			selectedOrEmpty = 'selected';
		}

		var listing = historyData[verId].details.verDate+' by '+historyData[verId].details.userName;

		// Note - we prepend `optionsHTML` because the `for( in )` loop will automatically order numerical keys
		// ASC, which we don't want.
		optionsHtml = '<option '+selectedOrEmpty+' data-version-id="'+verId+'">'+listing+'</option>'+optionsHtml;
	}

	var html = ''
		+ '<div class="dashboard">'

			+ '<div class="content_sized headed_box">'
				+ '<h2>Select Version</h2>'
				+ '<div class="spaced-lesser content_sized dashboard">'
					+ '<div class="content_sized" style="min-width: 5rem; max-width: 20rem">'
					+ '<select id="fs-history-versions" multiple class="minimal_scrollbars" style="width:100%">'
						+ optionsHtml
					+ '</select>'
					+ '</div>'

					+ '<div class="content_sized" style="min-width: 5rem; max-width: 20rem">'
					+ '<table class="property-table" >'
						+ '<tbody>'
							+ '<tr>'
								 +'<td>Date</td>'
								 +'<td id="fs-history-date"></td>'
							+'</tr>'
							+'<tr>'
								+'<td>Updated By</td>'
								+'<td id="fs-history-user"></td>'
							+'</tr>'
						+ '</tbody>'
					+ '</table>'
					+ '</div>'
				+ '</div>'

				+ '<div class="centered">'
					+ '<button disabled id="fs-history-submit" class="centered action">'
						+ 'Rollback to this Version'
					+ '</button>'
				+ '</div>'
			+ '</div>'

			+ '<div class="content_sized headed_box">'
				+ '<h2>File Preview</h2>'
				+ '<div><div id="fs-history-dropzone" class="dropzone" style="max-width: 32rem"></div></div>'
			+ '</div>'

		+ '</div>'
	;

	return html;
};

/**
 * Populate the dialog version widgets with details of a supplied version.
 * If `versionId` is null or unset, then instead clear out the widgets and disable the
 * reassignment/rollback button.
 * @param {jQuery} $rollbackBtn
 * @param previewDz
 * @param versionId
 * @param historyData
 * @private
 */
DropzoneHistoryUtil._populateWithVersion = function($rollbackBtn, previewDz, modalIdx, versionId, historyData) {

	var files = [];
	var userName = '';
	var verDate = '';
	var canRollback = false;

	if (versionId) {
		// Make a deep copy of an array of the files array
		var files = JSON.parse(JSON.stringify(historyData[versionId].files));
			verDate = historyData[versionId].details.verDate;
		userName = historyData[versionId].details.userName;
		canRollback = true;
	}
	DropzoneUtil._setMockFiles(previewDz, files);
	$('#fs-history-date').html(verDate);
	$('#fs-history-user').html(userName);
	$rollbackBtn.attr('disabled', !canRollback);

	//positionModal(modalIdx);
};