'use strict';

function _typeof(obj) {
	if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') {
		_typeof = function _typeof(obj) {
			return typeof obj;
		};
	} else {
		_typeof = function _typeof(obj) {
			return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype
				? 'symbol'
				: typeof obj;
		};
	}
	return _typeof(obj);
}

/**
 * File customizer.js.
 *
 * Theme Customizer enhancements for a better user experience.
 *
 * Contains handlers to make Theme Customizer preview reload changes asynchronously.
 */

/* global TyperCssVarFields */

(function($) {

	var TyperCssVars = {
		/**
		 * Get styles.
		 *
		 * @since 3.0.28
		 * @returns {Object}
		 */
		getStyles: function getStyles() {
			var style = $('#typer-css-vars'),
				styles = style.html().replace(':root{', '').replace('}', '').split(';'),
				stylesObj = {}; // Format styles as a object we can then tweak.

			_.each(styles, function(style) {
				style = style.split(':');

				if (style[0] && style[1]) {
					stylesObj[style[0]] = style[1];
				}
			});

			return stylesObj;
		},

		/**
		 * Builds the styles from an object.
		 *
		 * @since 3.0.28
		 * @param {Object} vars - The vars.
		 * @returns {string}
		 */
		buildStyle: function buildStyle(vars) {
			var style = '';

			_.each(vars, function(val, name) {
				val = val.toString();
				if ((name === '--media-max-height' || name === '--layout-max-width') && val !== '')
					if (val.indexOf('px') === -1)
						val += 'px';

				if (val !== '')
					style += name + ':' + val + ';';
			});

			return ':root{' + style + '}';
		},
	};

	function TyperHexToHsl(hex) {
		if (hex == null || hex == '') {
			return null;
		}

		hex = TyperRgb2Hex(hex);

		var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);

		var r = parseInt(result[1], 16);
		var g = parseInt(result[2], 16);
		var b = parseInt(result[3], 16);
		r /= 255;
		g /= 255;
		b /= 255;
		var max = Math.max(r, g, b),
			min = Math.min(r, g, b);
		var h,
			s,
			l = (max + min) / 2;

		if (max === min) {
			h = s = 0; // achromatic
		} else {
			var d = max - min;
			s = l > 0.5 ? d / (2 - max - min) : d / (max + min);

			switch (max) {
				case r:
					h = (g - b) / d + (g < b ? 6 : 0);
					break;

				case g:
					h = (b - r) / d + 2;
					break;

				case b:
					h = (r - g) / d + 4;
					break;
			}

			h /= 6;
		}

		var HSL = {};
		HSL.h = Math.ceil(h * 360);
		HSL.s = Math.round(s * 100) + '%';
		HSL.l = Math.round(l * 100) + '%';
		return HSL;
	}

	function TyperColorContrast(hexcolor, hsl) {
		hexcolor = TyperRgb2Hex(hexcolor);

		hexcolor = hexcolor.replace('#', '');

		if (hexcolor.length === 3) {
			hexcolor = hexcolor[0] + hexcolor[0] + hexcolor[1] + hexcolor[1] + hexcolor[2] + hexcolor[2];
		}

		const r = parseInt(hexcolor.substr(0, 2), 16);
		const g = parseInt(hexcolor.substr(2, 2), 16);
		const b = parseInt(hexcolor.substr(4, 2), 16);
		const yiq = ((r * 299) + (g * 587) + (b * 114)) / 1000;

		if (hsl) {
			return (yiq >= 154) ? '0, 0%, 0%' : '0, 0%, 100%';
		} else {
			return (yiq >= 154) ? '#000000' : '#ffffff';
		}
	}

	function TyperRgb2Hex(rgb) {
		if (rgb.indexOf('#') !== -1) {
			return rgb;
		}

		rgb = rgb.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i);
		return (rgb && rgb.length === 4) ? '#' +
			('0' + parseInt(rgb[1], 10).toString(16)).slice(-2) +
			('0' + parseInt(rgb[2], 10).toString(16)).slice(-2) +
			('0' + parseInt(rgb[3], 10).toString(16)).slice(-2) : '';
	}

	_.each(TyperCssVarFields, function(field) {
		wp.customize(field.settings, function(value) {

			value.bind(function(newVal) {
				var styles = TyperCssVars.getStyles();

				if (newVal == null || newVal == '') {
					return;
				}

				_.each(field.css_vars, function(cssVar) {
					var calcValue;

					if ('object' === _typeof(newVal)) {

						if (cssVar[2] && newVal[cssVar[2]]) {
							if ('object' === _typeof(newVal[cssVar[2]]) && newVal[cssVar[2]].hasOwnProperty('size') &&
								newVal[cssVar[2]].hasOwnProperty('unit')) {
								newVal[cssVar[2]] = newVal[cssVar[2]].size + newVal[cssVar[2]].unit.replace('-', '');
							}
							calcValue = cssVar[1].replace('$', newVal[cssVar[2]]);
							styles[cssVar[0]] = calcValue;
						} else {
							if (newVal.hasOwnProperty('size') && newVal.hasOwnProperty('unit')) {
								styles[cssVar] = newVal.size + newVal.unit.replace('-', '');
							}
						}

					} else {
						if (cssVar[1]) {
							if ('object' === _typeof(newVal) && newVal.hasOwnProperty('size') &&
								newVal.hasOwnProperty('unit')) {
								newVal = newVal.size + newVal.unit.replace('-', '');
							}
							calcValue = cssVar[1].replace('$', newVal);

							if (calcValue.indexOf('hex_to_hsl_') >= 0) {
								calcValue = calcValue.replace('hex_to_hsl_', '');
								var hsl = TyperHexToHsl(newVal);

								if (hsl) {
									calcValue = hsl[calcValue];
								} else {
									calcValue = hsl;
								}
							}

							if (calcValue === 'color_contrast') {
								calcValue = TyperColorContrast(newVal);
							}

							if (calcValue === 'color_contrast_hsl') {
								calcValue = TyperColorContrast(newVal, true);
							}
						} else {
							calcValue = newVal;
						}

						if (calcValue) {
							styles[cssVar[0]] = calcValue;
						}
					}
				});

				$('#typer-css-vars').html(TyperCssVars.buildStyle(styles));
			});
		});
	});

	wp.customize.bind('preview-ready', function() {
		wp.customize.preview.bind('active', function() {
			_.each(TyperCssVarFields, function(field) {

				wp.customize(field.settings, function(value) {
					var styles = TyperCssVars.getStyles(),
						newVal = window.parent.wp.customize(value.id).get();

					if (newVal == null || newVal == '') {
						return;
					}

					_.each(field.css_vars, function(cssVar) {
						if ('object' === _typeof(newVal)) {
							if (cssVar[2] && newVal[cssVar[2]]) {
								if ('object' === _typeof(newVal[cssVar[2]]) &&
									newVal[cssVar[2]].hasOwnProperty('size') &&
									newVal[cssVar[2]].hasOwnProperty('unit')) {

									styles[cssVar[0]] = cssVar[1].replace('$', newVal[cssVar[2]].size +
										newVal[cssVar[2]].unit.replace('-', ''));
								} else {
									styles[cssVar[0]] = cssVar[1].replace('$', newVal[cssVar[2]]);
								}
							} else {
								if (newVal.hasOwnProperty('size') && newVal.hasOwnProperty('unit')) {
									styles[cssVar] = newVal.size + newVal.unit.replace('-', '');
								}
							}
						} else {
							var calcValue;
							if (cssVar[1]) {
								if ('object' === _typeof(newVal) && newVal.hasOwnProperty('size') &&
									newVal.hasOwnProperty('unit')) {
									newVal = newVal.size + newVal.unit.replace('-', '');
								}

								calcValue = cssVar[1].replace('$', newVal);

								if (calcValue.indexOf('hex_to_hsl_') >= 0) {
									calcValue = calcValue.replace('hex_to_hsl_', '');
									var hsl = TyperHexToHsl(newVal);

									if (hsl) {
										calcValue = hsl[calcValue];
									} else {
										calcValue = hsl;
									}
								}

								if (calcValue === 'color_contrast') {
									calcValue = TyperColorContrast(newVal);
								}

								if (calcValue === 'color_contrast_hsl') {
									calcValue = TyperColorContrast(newVal, true);
								}
							} else {
								calcValue = newVal;
							}

							if (calcValue) {
								styles[cssVar[0]] = calcValue;
							}
						}
					});

					$('#typer-css-vars').html(TyperCssVars.buildStyle(styles));
				});
			});
		});
	});

})(jQuery);
