<?php

namespace modules\htmlEdit;

class main extends \moduleMain {
	
	use \modules\output\traits {
			\modules\output\traits::__construct as __ConstructOutput;
		}

	private $active = FALSE;
	
	public function __construct() {
		parent::__construct(__DIR__);
		$this->__ConstructOutput();
	}

	public function Activate() {
		hook_add('component.add', [$this, '__component']);
		hook_add('html.prepare', [$this, '__html_prepare']);
		hook_add('page.footer', [$this, '__page_footer']);		// add tinymce loader
	}

	// intercept textarea fields
	public function __component(&$status, $requested) {
		if ($requested == 'htmledit') {
			$this->active = TRUE;
		}
	}

	public function __html_prepare($modulemain) {
		if ($this->active) {
			$base = $this->StaticUriModule(__DIR__);
//			$id = $this->IncludeFile($base . '/tinymce.min.js');
			$id = $this->IncludeFile($base . '/tinymce.js', 'tinymce');
			$id->Version('');
		}
	}
	
	public function __page_footer(&$html) {
		if ($this->active) {
			$params = [ 
				'selector' => 'textarea.htmledit',
				'branding' => false,
				'convert_urls' => false,
				'browser_spellcheck' => true,
				'menubar' => 'edit insert view format table tools',
				'toolbar' => 'undo redo | fontselect styleselect fontsizeselect forecolor backcolor removeformat | bold italic | '.
							 'alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image | fullscreen code' ,
				'plugins' => [
					'advlist autolink lists link image anchor',		// preview charmap
					'searchreplace code fullscreen textcolor',		// visualblocks
					'media table contextmenu paste code',			// insertdatetime
				],
				'font_formats' => 'Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;Courier New=courier new,courier;Helvetica=helvetica;Tahoma=tahoma,arial,helvetica,sans-serif;Terminal=terminal,monaco;Times New Roman=times new roman,times;Verdana=verdana,geneva',
				'fontsize_formats' => '8pt 10pt 12pt 14pt 16pt 18pt 24pt 36pt 48pt 72pt',
			];
			$params = hook_execute('tinymce.init', $params);		// this is done very late so that theme-based hooks can be run
			$params = json_encode($params);

			// this will add the instance of the editor to the htmlarea
			$javascript = <<<'BLOCK'

	// 1. Allow TinyMCE window to interact within jQuery UI dialog
	var originalAllowInteraction = $.ui.dialog.prototype._allowInteraction;
	$.ui.dialog.prototype._allowInteraction = function(event) {
		if ($(event.target).closest('.mce-reset').length) {
			return true;
		}
		return originalAllowInteraction.apply(this, arguments);
	};

	// 2. Prevent jQuery UI dialog from stealing focus away from TinyMCE source view textarea
	$(document).on('mousedown', '.mce-reset textarea', function(e) {
		e.stopImmediatePropagation();
		var $ta = $(this);
		setTimeout(function() {
			$ta.focus();
		}, 0);
	});

	$(document).on('focusin', '.mce-reset textarea', function(e) {
		e.stopImmediatePropagation();
	});
	
	$(document).on('loaded.template', function(event, data, $container) {
		let param = {{params}};
		let $first = $(param.selector).first();
		let content = !$first.length ? '{}' : $first.attr('default') ?? '{}';
		content = JSON.parse(content);

		param.setup = function(editor) {
			editor.on('FullscreenStateChanged', (e) => {
				let fullscreen = e.state;
				$(document).trigger( 'fullscreen:tinymce', [ editor, fullscreen ] );
			});
		};
		if (typeof content.plugins == 'object' && Array.isArray(content.plugins)) {
			param.plugins =  param.plugins.concat(content.plugins);
		} else if (typeof content.plugins == 'string') {
			param.plugins.push(content.plugins);
		}
		if (typeof content.content_style == 'string') {
			param.content_style = content.content_style;
		}
		
		param.init_instance_callback = function(editor) {
			let original = editor.targetElm;
			original.tiny = editor;
			if (typeof content.fontsize != 'undefined') {
				editor.execCommand('FontSize', false, content.fontsize);
			}
			if (typeof content.fontfamily != 'undefined') {
				editor.execCommand('FontName', false, content.fontfamily);
			}
		};
		tinymce.init(param);
		
	}).on('formsubmit', function(event, $form, data) {
		
		$('textarea.htmledit', $form).each(function() {
			let content;
			if (typeof this.tiny != 'undefined') {
				content = this.tiny.getContent();
			} else {
				content = tinymce.get(this.id).getContent();
			}
			$(this).html( content );
			let name = this.name;
			let ok = false;
			for(let i = 0; i < data.length; i++) {
				if (data[i].name == name) {
					data[i].value = content;
					ok = true;
					break;
				}
			}
			if (!ok) {
				data.push({name: name, value: content});
			}
		});
	}).on('page.before', function(event, data) {
		if (typeof data.result == 'undefined' || !data.result) {
			tinymce.remove();
		}
	});
BLOCK;

			$javascript = str_replace('{{params}}', $params, $javascript);
			$id = $this->IncludeFile('');
			$id->JavascriptCommand($javascript, FALSE);
		}
	}
	
}
