"use strict";

$(function () {
	
	//! Initialize Bootstrap Tooltip
	
	var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
	var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
		return new bootstrap.Tooltip(tooltipTriggerEl)
	});
	
	//! Console Cheat: Display Bootstrap Modal Box
	
	if( (typeof uss[':alert'] === 'string') && uss[':alert'].trim() != '' ) {
		bootbox.alert({
			title: uss.platform,
			message: uss[':alert']
		});
	};
	
	/*!
		Console Cheat: Display Toastr Notification
		------------------------------------------
		
		Backend Sample:
		
			uss::console( ':toastr.error', "Error Text" );
			uss::console( ':toastr.success', "Success Text" );
			
		------------------------------------------------------
		
		To Avoid Overwritting A Message:
		A Custom "Dotted String" Should be appended:
		
			uss::console( 'toastr.error', "Error Text 1" );
			uss::console( 'toastr.error.2', "Error Text 2" );
			uss::console( 'toastr.error.custom', "Error Text 3" );
	*/
	
	Object.keys(uss).forEach(function(key) {
		let match = key.match(/^:toastr\.(?:error|info|warning|success)(?:\.[a-z0-9_\-]*)?$/i);
		if( !match ) return;
		let part = match[0].substr(1).split('.');
		let type = part[1];
		toastr[ type ]( uss[key], null, {
			progressBar: true,
			newestOnTop: false
		});
	});
	
	/*! 
		Preview An Image!
		-----------------
		
		<img src='' id='the-image-element />
		
		<input type='file' accept='image/*' data-uss-image-preview='#the-image-element' />
		
	*/
	
	$("input[type='file'][data-uss-image-preview]").each(function() {
		$(this).on('change', function() {
			try {
				let img = this.dataset.ussImagePreview;
				let image = $('img' + img);
				if( !image.length ) return console.error( `The image preview element cannot be found` );
				let reader = new FileReader();
				reader.addEventListener('load', function() {
					image.attr( 'src', this.result );
				});
				let file = this.files[0];
				let type = file.type.split('/')[0];
				if( type == 'image' ) reader.readAsDataURL( file );
				else toastr.error( 'Invalid Image file', null, {
					progressBar: true,
					showMethod: 'slideDown',
				});
			} catch(e) {
				console.log( e );
			};
		});
	});
	
	/*!
		========== confirm an anchor before redirecting =========
		
		<a href='' data-uss-confirm='The confirmation message'> 
			Click here to redirect 
		</a>
		
	*/
	
	$("a[data-uss-confirm]").on('click', function(e) {
		e.preventDefault();
		let anchor = this;
		let message = this.dataset.ussConfirm;
		if( !message || message.trim() == '' ) message = 'You are about to leave this page';
		bootbox.confirm({
			message: message,
			size: 'small',
			className: 'text-center animate__animated animate__faster animate__bounceIn',
			centerVertical: true,
			closeButton: false,
			callback: function(choice) {
				if( !choice ) return;
				let target = anchor.target;
				if( (!target || target == "_self") && !anchor.dataset.ussFeatures ) {
					window.location.href = anchor.href;
				} else {
					/*
						windowFeature Sample that works on Chrome:
						------------------------------------------
						resizable=yes, scrollbars=yes, titlebar=yes, width=300, height=300, top=10, left=10
					*/
					window.open( anchor.href, target, anchor.dataset.ussFeatures );
				}
			},
			onShow: function(e) {
				$(e.currentTarget).removeClass('fade');
			}
		});
	});
	
	/*!
		=================== confirm a form before submitting ===================
		
		<form method='POST' data-uss-confirm='The confirmation message'>
			...
		</form>
		
	*/
	
	$("form[data-uss-confirm]").on('submit', function(e) {
		e.preventDefault();
		let form = this;
		let message = this.dataset.ussConfirm;
		if( !message || message.trim() == '' ) message = 'Please confirm this process to continue';
		bootbox.confirm({
			message: `<div class='px-4'>${message}</div>`,
			className: 'text-center animate__animated animate__faster animate__bounceIn',
			size: 'small',
			callback: function(yea) {
				if( !yea ) return;
				let node = e.originalEvent.submitter;
				if( node.hasAttribute('name') ) {
					let nodeName = node.tagName.toLowerCase();
					let permit = [
						( nodeName == 'input' && node.type == 'submit' ),
						( nodeName == 'button' && ['submit', '', undefined].includes( node.type ) )
					];
					if( permit.includes(true) ) {
						let input = document.createElement('input');
						input.type = 'hidden';
						input.name = node.name;
						input.value = node.value;
						if( input.value == undefined ) input.value = '';
						form.appendChild( input );
					}
				};
				form.submit();
			},
			onShow: function(e) {
				$(e.currentTarget).removeClass('fade');
			},
			closeButton: false,
			centerVertical: true
		});
	});
	
	//! Copy a text on button click 
	
	$("[data-uss-copy]").click(function() {
		// get the element;
		let self = this;
		let el = $(this.dataset.ussCopy).get(0);
		if( !el ) return toastr.warning( "Failed to copy content" );
		// copy the text;
		let text;
		if( ['input', 'select', 'textarea'].includes( el.nodeName.toLowerCase() ) )
			text = el.value.trim();
		else text = el.innerText.trim();
		// add to clipboard
		navigator.clipboard.writeText( text ).then(
			() => toastr.info( self.dataset.ussMessage || 'Copied to clipboard' ),
			() => toastr.warning( 'Not copied to clipboard' )
		);
	});
	
	/*!
		=========== Auto select an option from the <select/> element ===========
		Make select work similar to input
	*/
	
	$("select[value]").each(function() {
		let value = this.getAttribute('value');
		if( value == '' ) return;
		this.value = value;
	});
	
	/*
		Convert a textarea into Quill Editor;
		-------------------------------------
		
		Please Note that the textarea to Quill converter is just a quick fix to help you create a 
		WYSIWYG editor with the most minimal Tool!
		
		If you need an advance Quill Features or a Custom Editor,
		You should create it personally
		
	*/
	
	Quill.register("modules/imageCompressor", imageCompressor);
	
	$('textarea[data-uss-editor]').each(function() {
		
		let el = this;
		let editorTheme = ( el.dataset.ussEditor|| 'bubble' ).trim();
		
		//! Create Elements;
		let container = document.createElement('div');
		let block = document.createElement('div');
		
		//! Preset Attributes;
		container.setAttribute('class', `uss-quill-container uss-quill-${editorTheme}`);
		
		//! Arrange Elements;
		el.before(container);
		container.appendChild(block);
		container.appendChild(el);
		
		//! Prepare Most Minimal Toolbar
		let widget = [
			//[{ 'size': ['small', 'normal', 'large'] }],
			[ 'bold', 'italic', 'underline' ],
			//[{ 'script': 'super' }, { 'script': 'sub' }],
			//[{ 'header': '1' }, { 'header': '2' }, 'blockquote', 'code-block' ],
			[{ 'list': 'ordered' }, { 'list': 'bullet'}],
			[ 'link', 'image', 'clean' ]
		];
		
		//! Quill Configuration;
		let config = {
			theme: editorTheme,
			placeholder: el.placeholder || 'Type here',
			modules: {
				toolbar: widget, //widget
				imageResize: {
					displaySize: true
				},
				imageCompressor: {
					quality: 0.7,
					maxWidth: 790,
					maxHeight: 790,
					imageType: 'image/png',
					debug: true
				}
			}
		};
		
		
		let quill = new Quill(block, config);
	
		//! Create function to check if Quill content is empty;
		quill.isEmpty = function() {
			if ((quill.getContents()['ops'] || []).length !== 1) { return false }
			return quill.getText().trim().length === 0
		};
		
		//! send initial value from textarea into the quill editor;
		quill.clipboard.dangerouslyPasteHTML(0, el.value);
		
		//! get the rows attribute described in the <textarea/> element
		if( el.rows ) {
			let styles = window.getComputedStyle( quill.root );
			let para = window.getComputedStyle( $(quill.root).find('p').get(0) );
			let size = {
				fontsize: parseInt( para.fontSize ),
				paddingY: parseInt( styles.padding ) * 2,
				borderY: parseInt( styles.borderWidth ) * 2,
				lineHeight: parseInt( para.lineHeight )
			};
			let rows = size.paddingY + size.borderY + ( size.lineHeight * parseInt(el.rows) );
			quill.root.style.minHeight = `${rows}px`;
		};
		
		//! send quill value into the textarea
		if( config.theme == 'bubble' ) {
			let info = document.createElement('div');
			info.setAttribute('class', 'fs-12px text-info text-end mb-1 uss-quill-info');
			info.innerHTML = `<i class='mdi mdi-alert-circle-outline'></i> select a text to format it`;
			container.prepend(info);
		};
		
		$(quill.root).addClass( el.getAttribute('class') || '' );
		
		// window.quill = quill;
		
		quill.on('text-change', function() {
			el.value = quill.isEmpty() ? '' : quill.root.innerHTML;
		});
		
	});
	
});
