// +-------------------------------------------------+
// © 2002-2004 PMB Services / www.sigb.net pmb@sigb.net et contributeurs (voir www.sigb.net)
// +-------------------------------------------------+
// $Id: actionZone.js,v 1.44 2024/07/26 09:01:00 tsamson Exp $

define([
	"dojo/_base/declare",
	"dojo/dom",
	"dijit/_Widget",
	"dojo/topic",
	"dojo/_base/lang",
	"dijit/registry",
	"dijit/form/Button",
	"dojo/dom-construct",
	"app/warningMessage",
	"dojox/dtl/_base",
	"dojox/dtl/Context",
	"app/workZone",
	"dojo/on",
  ],
function (declare, dom, widget, topic, lang, registry, Button, domConstruct, warningMessage, dtl, Context, workZone, on) {
	return declare(widget, {

		params: null,
		exitButton: null,
		checkoutButton: null,
		printTicketButton: null,
		backButton: null,
		bookingButton: null,
		buttonDiv: null,
		workContainer: null,
		postCreate: function() {

			/** Abonnement aux évenements provenants de la classe "readerDatas" **/
			this.own(
				topic.subscribe("readerDatas", lang.hitch(this, this.handleEvents)),
				topic.subscribe("contentZone", lang.hitch(this, this.handleEvents)),
				topic.subscribe("actionZone", lang.hitch(this, this.handleEvents)),
				topic.subscribe("warningMessage", lang.hitch(this, this.handleEvents))
			);

			this.params = dojoConfig.bibloto.appParams;

			/** Instanciation/Création de la div contenant les différents boutons de controle **/
			this.buttonDiv = domConstruct.create('div', {
				id: 'contentButton',
				class: 'contentButton',
				style: {
					margin: '0 auto',
					width: '50%'
				}
			}, this.domNode);

			this.initButtons();

			/** Instanciation/Création de la div contenant les messages relatifs à une action + le bouton terminer (terminer l'action) **/
			this.workContainer = new workZone(this.domNode);
		},

		handleEvents: function(evtType, evtArgs) {
			switch (evtType) {
				case 'contentReady':
					/**
					 * Action selon le paramétrage
					 * voir reader datas pour le mode enabled by default ? apres les datas user reçues
					 */
					switch (this.params.default_action) {
						case '0':
							//Cas affichage boutons par défault
							topic.publish('actionZone', 'stopListen');
							break;
						case '1':
							//Cas affichage prêts directs
							this.checkout();
							break;
						case '2':
							//Cas affichage retour direct
							this.checkin();
							break;
						case '3':
							//Cas d'affichage des résas direct
							this.book();
							break;
					}
					break;

				case 'erase':
				case 'warnMembershipDateExpired':
                    if (dojoConfig.bibloto.appParams.default_action_end == 0) {
                        this.endAction();
                    }

                    if(dojoConfig.bibloto.appParams.trombinoscope_enabled == 1 && dojoConfig.bibloto.appParams.trombinoscope_auth == 1) {
                        xhr(dojoConfig.bibloto.appParams.opac_url + "auth.php?action=logout");
                    }
					topic.publish('actionZone', 'actionZoneErased');
					if (this.params.msg_action_title) {
						dom.byId('infoState').innerHTML = "<span><span id='title_infos'>" + this.params.msg_action_title + "</span></span>";
					} else {
						dom.byId('infoState').innerHTML = "";
					}
					break;
			}
		},

		/** Instanciation des différents boutons de controle en fonction du paramétrage de l'appli **/
		initButtons: function() {
			if (parseInt(this.params.checkout_activate)) {

				/** Creation du bouton emprunter un livre **/
				this.checkoutButton = new Button({
					label: this.params.msg_checkout_button,
					onClick: lang.hitch(this, this.checkout),
				}, domConstruct.create('div', {
					id: 'checkoutButton'
				}, this.buttonDiv)).startup();

			}
			if (parseInt(this.params.checkin_activate)) {

				/** Création du bouton rendre un livre **/
				this.backButton = new Button({
					label: this.params.msg_checkin_button,
					onClick: lang.hitch(this, this.checkin),
				}, domConstruct.create('div', {
					id: 'checkinButton'
				}, this.buttonDiv)).startup();
			}

			if (parseInt(this.params.resa_activate)) {

				/** Création du bouton réserver un livre **/
				this.bookingButton = new Button({
					label: this.params.msg_resa_button,
					onClick: lang.hitch(this, this.book),
				}, domConstruct.create('div', {
					id: 'bookingButton'
				}, this.buttonDiv)).startup();
			}

			/** Création du bouton exit (publie un evt -> clean datas empr + retour homepage) **/
			this.exitButton = new Button({
				label: this.params.msg_exit_button,
				onClick: lang.hitch(this, this.backHomepage),
			}, domConstruct.create('div', {
				id: 'exitButton'
			}, this.buttonDiv)).startup();

			if (this.params.msg_action_title) {
				dom.byId('infoState').innerHTML = "<span id='container_action_actions'><span id='title_infos'>" + this.params.msg_action_title + "</span></span>"
			} else {
				dom.byId('infoState').innerHTML = "";
			}


			if (parseInt(this.params.email_activate)) {
				let sendEmail = domConstruct.create('input', {
					type: "button",
					value: dojoConfig.bibloto.appParams.msg_email_button,
					className: 'sendMailPretButton'
				});
				domConstruct.place(sendEmail, 'container_action_actions');
				on(sendEmail, 'click', lang.hitch(this, this.sendMailPret));
			}
			if (dojoConfig.printer_id) {
				if ((parseInt(dojoConfig.bibloto.appParams.printer_activate) > 0) && parseInt(dojoConfig.bibloto.appParams.print_all_loans_activate)) {
					let printLoans = domConstruct.create('input', {
						type: "button",
						value: dojoConfig.bibloto.appParams.msg_print_all_loans,
						className: 'printLoansButton'
					});
					domConstruct.place(printLoans, 'container_action_actions');
					on(printLoans, 'click', lang.hitch(this, this.printLoans));
				}
			}
			//bouton de connexion externe
			if (dojoConfig.bibloto.appParams.force_ext_auth) {
				var extAuthButton = document.getElementById('ext_auth_button');
				if (extAuthButton) {
					on(extAuthButton, 'click', function(){
						topic.publish('buffer', 'extAuth', {
							elt : null
						});
					});
				}
			}
			//TODO: Se baser sur les parametres fourni par la source pour instancier les bon boutons en fonction des droits
		},

		/** Fonction appelée lors du retour à la page d'accueil **/
		backHomepage: function() {
			//Publish event, nettoyage des différents parametres renseignés + back to homepage
			topic.publish('actionZone', 'erase');
			document.getElementById("keyboard").focus();
		},

		/** Fonction des prêts **/
		checkout: function() {
			/**
			 * Faire un prêt
			 * Publication d'un event change mode + enable lecture cb pour pret ///// Affichage du panneau "Présentez un exemplaire"
			 */

			this.hideContainers();
			let loanActionDatas = registry.byId('loanActionDatas');
			loanActionDatas.resetDatas();
			loanActionDatas.domNode.style.display = "";
			loanActionDatas.render();
			this.buttonDiv.style.display = "none";
			this.workContainer.show();
			this.setMessage(this.params.msg_dialog_place_item_checkout);


			if (this.params.msg_checkout_title) {
				dom.byId('infoState').innerHTML = "<span id='container_action_checkout'><span id='title_infos'>" + this.params.msg_checkout_title + "</span></span>";
			} else {
				dom.byId('infoState').innerHTML = '';
			}

			topic.publish('actionZone', 'enableLoan');

			if (parseInt(this.params.email_activate)) {
				let sendEmail = domConstruct.create('input', {
					type: "button",
					value: dojoConfig.bibloto.appParams.msg_email_button,
					className: 'sendMailPretButton'
				});
				domConstruct.place(sendEmail, 'container_action_checkout');
				on(sendEmail, 'click', lang.hitch(this, this.sendMailPret));
			}
			if (dojoConfig.printer_id) {
				if ((parseInt(dojoConfig.bibloto.appParams.printer_activate) > 0) && parseInt(dojoConfig.bibloto.appParams.print_all_loans_activate)) {
					let printLoans = domConstruct.create('input', {
						type: "button",
						value: dojoConfig.bibloto.appParams.msg_print_all_loans,
						className: 'printLoansButton'
					});
					domConstruct.place(printLoans, 'container_action_checkout');
					on(printLoans, 'click', lang.hitch(this, this.printLoans));
				}
			}
			document.getElementById("keyboard").focus();
		},

		/** Fonction d'impression ticket **/
		printTicket: function() {
			/**
			 * Faire l'impression du ticket
			 */
			let templateObj = new dtl.Template(this.params.printer_tpl);
			let contextObj = new Context(dojoConfig.bibloto.readerDatas.emprInfos);
			let compiledTemplate = templateObj.render(contextObj);
			let applet = document.jzebra;

			if (applet != null) {
				this.printer_finding(applet, compiledTemplate);
			}
		},

		printer_finding: function(applet, text) {
			applet.findPrinter(this.params.printer_name);
			if (!applet.isDoneFinding()) {
				//window.setTimeout(lang.hitch(this, this.printer_finding(applet,text), 100));
				//console.debug('printer not found (isDoneFinding)');
				return;
			}

			if (applet.getPrinter()) {
				applet.setEncoding(850);
				applet.append(text);
				applet.print();
			}
		},

		/** Fonction des retours **/
		checkin: function() {
			this.hideContainers();
			let containerback = registry.byId('backDatas');
			containerback.resetDatas();
			containerback.domNode.style.display = "";
			containerback.render();
			this.buttonDiv.style.display = "none";
			this.workContainer.show();
			this.setMessage(this.params.msg_dialog_place_item_checkin);

			if (this.params.msg_checkin_title) {
				dom.byId('infoState').innerHTML = "<span id='container_action_checkin'><span id='title_infos'>" + this.params.msg_checkin_title + "</span></span>";
			} else {
				dom.byId('infoState').innerHTML = '';
			}

			topic.publish('actionZone', 'enableBack');

			if (parseInt(this.params.email_activate)) {
				let sendEmail = domConstruct.create('input', {
					type: "button",
					value: dojoConfig.bibloto.appParams.msg_email_button,
					className: 'sendMailPretButton'
				});
				domConstruct.place(sendEmail, 'container_action_checkin');
				on(sendEmail, 'click', lang.hitch(this, this.sendMailPret));
			}
			if (dojoConfig.printer_id) {
				if ((parseInt(dojoConfig.bibloto.appParams.printer_activate) > 0) && parseInt(dojoConfig.bibloto.appParams.print_all_loans_activate)) {
					let printLoans = domConstruct.create('input', {
						type: "button",
						value: dojoConfig.bibloto.appParams.msg_print_all_loans,
						className: 'printLoansButton'
					});
					domConstruct.place(printLoans, 'container_action_checkin');
					on(printLoans, 'click', lang.hitch(this, this.printLoans));
				}
			}
			document.getElementById("keyboard").focus();
		},

		/** Affichage de l'écran des réservations **/
		book: function() {
			//this.hideContainers();
			let resaDatas = registry.byId('resaDatas');
			resaDatas.domNode.style.display = "";

			if (this.params.msg_resa_title) {
				dom.byId('infoState').innerHTML = "<span id='container_action_resa'><span id='title_infos'>" + this.params.msg_resa_title + "</span></span>"
			} else {
				dom.byId('infoState').innerHTML = "";
			}

			if (parseInt(this.params.email_activate)) {
				let sendEmail = domConstruct.create('input', {
					type: "button",
					value: dojoConfig.bibloto.appParams.msg_email_button,
					className: 'sendMailPretButton'
				});
				domConstruct.place(sendEmail, 'container_action_resa');
				on(sendEmail, 'click', lang.hitch(this, this.sendMailPret));
			}
			if (dojoConfig.printer_id) {
				if ((parseInt(dojoConfig.bibloto.appParams.printer_activate) > 0) && parseInt(dojoConfig.bibloto.appParams.print_all_loans_activate)) {
					let printLoans = domConstruct.create('input', {
						type: "button",
						value: dojoConfig.bibloto.appParams.msg_print_all_loans,
						className: 'printLoansButton'
					});
					domConstruct.place(printLoans, 'container_action_resa');
					on(printLoans, 'click', lang.hitch(this, this.printLoans));
				}
			}
			resaDatas.render();
		},

		sendMailPret: function() {
			topic.publish('actionZone', 'sendMailPret');
		},
		/**
		 * Fonction permettant d'imprimer la liste de tous les prêts de l'usager
		 */
		printLoans: function() {
			//On récupère le template d'impression des prêts de l'emprunteur
			let emprLoanPromise = dojoConfig.bibloto.jsonRpcServer.pmbesSelfServices_get_loans_printer_template(dojoConfig.bibloto.readerDatas.emprCb, "");
			emprLoanPromise.addCallback(lang.hitch(this, function(tpl) {
				let printer_id = dojoConfig.printer_id;
				let raspberry_ip = '';

				let temp = dojoConfig.bibloto.appParams.printer_name.split('@');
				raspberry_ip = temp[1];

				//On envoie l'impression
				let xhr = new XMLHttpRequest();
				xhr.open('POST', 'https://' + raspberry_ip + '/print?', true);
				xhr.setRequestHeader('Content-type', 'text/plain;charset=utf-8');
				xhr.send(
					JSON.stringify(
						{
							idPrinter: printer_id,
							xml: tpl.print_tpl
						}
					)
				);
			}));
		},

		/** Set le message de la zone d'action **/
		setMessage: function(msg, error) {
			this.workContainer.setMsg(msg, error);
		},

		/** Fonction de masquage des dontainers loanDatas & resaDatas (en fct du paramétrage) **/
		hideContainers: function() {
			if (parseInt(this.params.checkin_activate)) {
				if (registry.byId('loanDatas'))
					registry.byId('loanDatas').domNode.style.display = "none";
				if (registry.byId('loanActionDatas'))
					registry.byId('loanActionDatas').domNode.style.display = "none";
			}
			if (parseInt(this.params.resa_activate)) {
				if (registry.byId('resaDatas'))
					registry.byId('resaDatas').domNode.style.display = "none";
				if (registry.byId('loanActionDatas'))
					registry.byId('loanActionDatas').domNode.style.display = "none";
			}
			if (parseInt(this.params.checkout_activate)) {
				if (registry.byId('backDatas'))
					registry.byId('backDatas').domNode.style.display = "none";
			}
		},

		/**
		 * Fct éxecutée à l'appui sur le bouton terminer
		 * -> arrête l'écoute et masque le workContainer (affichage de l'expl posé sur la platine + boutons décisionnels)
		 */
		endAction: function() {
			topic.publish('actionZone', 'stopListen');
			this.buttonDiv.style.display = "";
			this.workContainer.hide();
			this.hideContainers();

			/** Switch selon le parametre défini dans le connecteur **/
			if (this.params.default_action_end == 0) {
				if (registry.byId('loanDatas')) {
					let loanDatas = registry.byId('loanDatas');
					if (loanDatas.domNode) {
						loanDatas.domNode.style.display = "";
					}
					loanDatas.render();
				}
				registry.byId('mainContainer').resize();

				if (this.params.msg_action_title) {
					dom.byId('infoState').innerHTML = "<span id='container_action_loanDatas'><span id='title_infos'>" + this.params.msg_action_title + "</span></span>";
				} else {
					dom.byId('infoState').innerHTML = "";
				}

				if (parseInt(this.params.email_activate)) {
					let sendEmail = domConstruct.create('input', {
						type: "button",
						value: dojoConfig.bibloto.appParams.msg_email_button,
						className: 'sendMailPretButton'
					});
					domConstruct.place(sendEmail, 'container_action_loanDatas');
					on(sendEmail, 'click', lang.hitch(this, this.sendMailPret));
				}
				if (dojoConfig.printer_id) {
					if ((parseInt(dojoConfig.bibloto.appParams.printer_activate) > 0) && parseInt(dojoConfig.bibloto.appParams.print_all_loans_activate)) {
						let printLoans = domConstruct.create('input', {
							type: "button",
							value: dojoConfig.bibloto.appParams.msg_print_all_loans,
							className: 'printLoansButton'
						});
						domConstruct.place(printLoans, 'container_action_loanDatas');
						on(printLoans, 'click', lang.hitch(this, this.printLoans));
					}
				}
			} else {
				//(this.params.msg_action_title)?dom.byId('infoState').innerHTML="<span>"+this.params.msg_action_title+"</span>":dom.byId('infoState').innerHTML="";
				this.backHomepage();
			}
		},
	});
});
