/**
 * WP PowerSuite — Customizer footer toolbar.
 */
(function ($) {
	'use strict';

	var cfg = typeof wppsCrPanel !== 'undefined' ? wppsCrPanel : {};
	var nonce = cfg.nonce || {};
	var labels = cfg.labels || {};

	function init() {
		if (!$('#customize-footer-actions').length) {
			return;
		}

		var $wrap = $('<div class="wpps-cr-panel-footer"></div>');
		var $reset = $('<button type="button" class="button button-primary wpps-cr-panel-reset"></button>')
			.text(labels.reset || 'Reset')
			.on('click', onReset);
		var $export = $('<button type="button" class="wpps-cr-panel-icon" title="' + (labels.export || 'Export') + '"><span class="dashicons dashicons-download"></span></button>')
			.on('click', onExport);
		var $import = $('<button type="button" class="wpps-cr-panel-icon" title="' + (labels.import || 'Import') + '"><span class="dashicons dashicons-upload"></span></button>')
			.on('click', function () { $file.trigger('click'); });
		var $more = $('<a class="wpps-cr-panel-icon wpps-cr-panel-more"></a>')
			.attr('href', cfg.adminPageUrl || '#')
			.attr('target', '_blank')
			.text(labels.more || 'Backup & more');

		var $file = $('<input type="file" accept=".json,.dat" style="display:none">').on('change', onImportFile);

		$wrap.append($reset, $export, $import, $more, $file);
		$('#customize-footer-actions').prepend($wrap);
	}

	function onReset(e) {
		e.preventDefault();
		if (!confirm(cfg.confirmReset || 'Reset customizer settings?')) {
			return;
		}
		var $btn = $(this).prop('disabled', true);
		$.post(ajaxurl, {
			action: 'wpps_cr_reset',
			nonce: nonce.reset,
			reset_css: '0'
		}).done(function (r) {
			if (r && r.success) {
				if (window.wp && wp.customize && wp.customize.state) {
					wp.customize.state('saved').set(true);
				}
				location.reload();
			}
		}).always(function () {
			$btn.prop('disabled', false);
		});
	}

	function onExport(e) {
		e.preventDefault();
		$.post(ajaxurl, {
			action: 'wpps_cr_export',
			nonce: nonce.export,
			format: 'json'
		}).done(function (r) {
			if (!r || !r.success || !r.data) {
				return;
			}
			var blob = new Blob([JSON.stringify(r.data, null, 2)], { type: 'application/json' });
			var a = document.createElement('a');
			a.href = URL.createObjectURL(blob);
			a.download = 'customizer-' + (r.data.stylesheet || 'export') + '-' + Date.now() + '.json';
			document.body.appendChild(a);
			a.click();
			document.body.removeChild(a);
			URL.revokeObjectURL(a.href);
		});
	}

	function onImportFile() {
		var file = this.files && this.files[0];
		if (!file) {
			return;
		}
		if (!confirm(cfg.confirmImport || 'Import will overwrite current settings. Continue?')) {
			this.value = '';
			return;
		}
		var fmt = /\.dat$/i.test(file.name) ? 'dat' : 'json';
		var reader = new FileReader();
		var input = this;
		reader.onload = function (ev) {
			var raw = ev.target.result;
			var payload = raw;
			if (fmt === 'json') {
				try {
					var parsed = JSON.parse(raw);
					if (parsed.template && cfg.currentTemplate && parsed.template !== cfg.currentTemplate) {
						if (!confirm('This file is for parent theme "' + parsed.template + '". Current theme is "' + cfg.currentTemplate + '". Import anyway?')) {
							input.value = '';
							return;
						}
					}
					payload = JSON.stringify(parsed);
				} catch (err) {
					alert('Invalid JSON file');
					input.value = '';
					return;
				}
			}
			$.post(ajaxurl, {
				action: 'wpps_cr_import',
				nonce: nonce.import,
				import_data: payload,
				format: fmt,
				import_images: '1'
			}).done(function (r) {
				if (r && r.success) {
					location.reload();
				} else {
					var msg = (r && r.data && r.data.message) ? r.data.message : (r && r.data) || 'Import failed';
					alert(msg);
				}
				input.value = '';
			}).fail(function () {
				alert('Import failed');
				input.value = '';
			});
		};
		reader.readAsText(file);
	}

	$(function () {
		if (typeof wp !== 'undefined' && wp.customize) {
			wp.customize.bind('ready', init);
		} else {
			init();
		}
	});
})(jQuery);
