// +-------------------------------------------------+
// © 2002-2004 PMB Services / www.sigb.net pmb@sigb.net et contributeurs (voir www.sigb.net)
// +-------------------------------------------------+

// Copie adaptee de apps/search_dsi/EntityForm.js pour le module ImportExport
// (RMC, cf. devel/impex-evolutions.md E9) : convention deja suivie par les
// autres modules consommateurs (search_dsi, search_universes, frbr), chacun
// avec sa propre copie plutot qu'un partage direct.

define([
        "dojo/_base/declare",
        "dojo/_base/lang",
        "dojo/on",
        "dojo/dom",
        "dijit/registry",
        "apps/pmb/PMBDojoxDialogSimple",
        "apps/pmb/pmbEventsHandler",
		"dojo/dom-construct",
		"dojo/query"
        ],
		function(declare, lang, on, dom, registry, DialogSimple, pmbEventsHandler, domConstruct, query){
	return declare(null, {
		className: null,
		indexation: null,
		signals: null,
		dijits:null,
		formName:null,
		constructor: function(params){
			lang.mixin(this, params);

            this.signals = [];
            this.dijits = {};

			this.init();
		},

		handleEvents: function(evtType,evtArgs){
			switch(evtType){
				case 'leafRootClicked':
				case 'leafClicked':
					this.destroy();
					break;
				default:
					if (typeof this[evtType] == 'function') {
						this[evtType](evtArgs);
					}
					break;
			}
		},

		init: function(){
			pmbEventsHandler.initEvents(this);
		},

		destroy:function(){
			this.signals.forEach(function(signal) {
				signal.listner.remove();
			});
			this.dijits.forEach(function(dijit) {
				dijit.destroyRecursive();
				dijit.destroy();
			});
		},

		loadDialog : function(params, evt, path) {
			let dijitId = params.entity_type + "_dialog";

			if(!this.dijits[dijitId]) {
                // Suppression + creation de la dialog
				this.destroyDialog(dijitId);
				this.dijits[dijitId] = new DialogSimple({
					title: pmbDojo.messages.getMessage('importexport', 'ie_rmc_form_title'),
					executeScripts: true,
					id: dijitId,
					style: {
						width:'85%'
					}
				});

				this.dijits[dijitId].attr('href', path);
				this.dijits[dijitId].startup();

				// Gestion des event de la modal dojo
				this.addSignal(dijitId, on(this.dijits[dijitId], "load", lang.hitch(this, function() {
					pmbEventsHandler.initEvents(this, dom.byId(dijitId));
					pmbEventsHandler.formToAjax(dom.byId(dijitId));
					ajax_parse_elements();
				})));
				this.addSignal(dijitId, on(this.dijits[dijitId], "hide", lang.hitch(this, function() {
					this.destroyDialog(dijitId);
				})));
			}

			// On ajoute le button pour extand le dialog
			this.addExpandButton(this.dijits[dijitId]);

            // On calcule sa taille et on l'affiche
			this.dijits[dijitId].resize();
			this.dijits[dijitId].show();

			return this.dijits[dijitId];
		},

		hideDialog : function(params) {
			if (!params.className) {
				params.className = this.className;
			}

			let dijitId = params.entity_type + "_dialog";
			if (this.dijits[dijitId]) {
				this.dijits[dijitId].hide();
			} else {
				this.destroyDialog(params.entity_type + "_dialog");
			}
		},

		removeDialog : function(params) {
			this.destroyDialog(params.entity_type + "_dialog");
		},

		destroyDialog : function(dijitId) {
			let myDijit = registry.byId(dijitId);
            if (myDijit) {
				myDijit.destroyDescendants();
                myDijit.destroy();
                myDijit.destroyRendering();
            }

			if (this.dijits[dijitId]) {
				delete this.dijits[dijitId];
			}

			let signalRemoved = [];
            for (let index in this.signals) {
                let signal = this.signals[index];
                if (signal && signal.dialoagId == dijitId) {
                    signal.listner.remove();
                    signalRemoved.push(index);
                }
            }
            for (let index of signalRemoved) {
                this.signals.splice(index, 1);
            }
		},

		addSignal: function(dijitId, signal) {
			this.signals.push({
				dialoagId: dijitId,
				listner: signal
			});
		},

		addExpandButton: function(dialog) {
			if (dialog && !query(".customExpandBtn", dialog.titleBar).length) {

				// Creer le bouton d'expansion
				const expandBtn = domConstruct.create("span", {
					class: "customExpandBtn",
					title: pmbDojo.messages.getMessage('common', 'maximize'),
					role: "button",
					tabIndex: -1
				});

				// Ajouter l'icone
				const icon = domConstruct.create("i", {
					class: "fa fa-window-maximize",
					"aria-hidden": "true"
				});

				// Ajouter l'icone a l'element bouton
				domConstruct.place(icon, expandBtn);

				// Inserer avant le bouton de fermeture
				var closeBtn = query(".dijitDialogCloseIcon", dialog.titleBar)[0];
				domConstruct.place(expandBtn, closeBtn, "before");

				setInterval(() => {
					if (dialog.get("expanded") && !icon.className.includes("restore")) {
						icon.className = "fa fa-window-restore";
						icon.title = pmbDojo.messages.getMessage('common', 'minimize')
						return;
					}

					if(!dialog.get("expanded") && icon.className.includes("restore")) {
						icon.className = "fa fa-window-maximize";
						icon.title = pmbDojo.messages.getMessage('common', 'maximize');
						return;
					}
				}, 200)

				// Action sur clic
				on(expandBtn, "click", function(){
					dialog.toggleSize();
				});
			}
		}
	});
});
