// +-------------------------------------------------+
// © 2002-2004 PMB Services / www.sigb.net pmb@sigb.net et contributeurs (voir www.sigb.net)
// +-------------------------------------------------+
// $Id: loanContainer.js,v 1.26 2023/02/17 08:38:39 dbellamy Exp $

define(["dojo/_base/declare", "dojox/grid/DataGrid", "dojo/topic", "dojo/_base/lang", "dojo/dom-construct", "dijit/registry", "dojo/store/Memory", "dojo/data/ObjectStore", "dijit/registry", "app/warningMessage", "dojo/dom", 'dijit/form/Button'], function(declare, DataGrid, topic, lang, domConstruct, registry, Memory, ObjectStore, registry, warningMessage, dom, Button) {
    return declare(null, {
        dataGrid : null,
        structure : null,
        loanStore : null,
        datasLoan : null,
        antivol_level : 0,
        readingEnabled : true,
        
        constructor : function() {
            /**
             * Création du store de prêt
             * Instanciation du datagrid
             *
             */
            this.datasLoan = new Array();
            for (var i = 0; i < dojoConfig.bibloto.readerDatas.emprInfos.prets.length; i++) {            			
                this.datasLoan.push({
                    "title" : dojoConfig.bibloto.readerDatas.emprInfos.prets[i].icondoc + dojoConfig.bibloto.readerDatas.emprInfos.prets[i].title,
                    "icondoc" : dojoConfig.bibloto.readerDatas.emprInfos.prets[i].icondoc,
                    "loan_date" : dojoConfig.bibloto.readerDatas.emprInfos.prets[i].date_pret,
                    'loan_back_date' : dojoConfig.bibloto.readerDatas.emprInfos.prets[i].date_retour,
                    'pret_retard' : dojoConfig.bibloto.readerDatas.emprInfos.prets[i].pret_retard,
                    'is_self_renew' : dojoConfig.bibloto.readerDatas.emprInfos.prets[i].is_self_renew,
                    'cb' : dojoConfig.bibloto.readerDatas.emprInfos.prets[i].cb,
                    'id' : i,       
                });
            }
            
            this.loanStore = new ObjectStore({
                idProperty : 'title',
                objectStore : new Memory({
                    data : this.datasLoan
                })
            });
            
            var info_nb_pret = '';            
            if (this.loanStore.objectStore.data.length > 0) {
            	info_nb_pret = ' (' + this.loanStore.objectStore.data.length + ')';
            } 
               
            this.structure = [{
                name : dojoConfig.bibloto.appParams.msg_expl_checkout_list_title + " <span>" + info_nb_pret + "</span>",
                field : "title",
                editable : false,
                width : "60%",
            }, {
                name : dojoConfig.bibloto.appParams.msg_expl_date_checkout,
                field : "loan_date",
                editable : false,
            }, {
                name : dojoConfig.bibloto.appParams.msg_expl_date_checkin,
                field : "loan_back_date",
                editable : false,       
                formatter : lang.hitch(this, this.formatProlonge ),
            }];           
            
            this.dataGrid = new DataGrid({
                store : this.loanStore,
                autoHeight : true,
                escapeHTMLInData: false,
				onStyleRow: lang.hitch(this, this.styleRow),
                query : {
                    id : "*"
                },
                structure : this.structure
            }, domConstruct.create('div', {
                id : 'loanDatas',
                style : {
                    height : '300px',
                    width : 'auto'
                }
            }, registry.byId('contentZone').domNode));

            this.dataGrid.startup();

            topic.subscribe('actionZone', lang.hitch(this, this.handleEvents));
            topic.subscribe('warningMessage', lang.hitch(this, this.handleEvents));
        },
        
        handleEvents : function(evtType, evtArgs) {
            //console.log('evt received in loanContainer', evtType, evtArgs);
            switch(evtType) {
            /**
             * pret evt recu
             */
            case 'explLent':
                this.antivol_level = 0;
                this.addToStore(evtArgs.response, keyboard_cb_enter);
                //console.log(evtArgs.response);
                if (dojoConfig.bibloto.appParams.rfid_activate == 1 && dojoConfig.bibloto.appParams.rfid_security_activate && evtArgs.response.expl_cb != keyboard_cb_enter) {
                    init_rfid_antivol_all_flag = 1;
                    init_rfid_antivol_all_level = 0;
                }
                break;
            case 'explBack':
                this.antivol_level = 1;
                this.popFromStore(evtArgs.response);
                if (dojoConfig.bibloto.appParams.rfid_activate == 1 && dojoConfig.bibloto.appParams.rfid_security_activate && evtArgs.response.expl_cb != keyboard_cb_enter) {
                    init_rfid_antivol_all_flag = 1;
                    init_rfid_antivol_all_level = 1;
                }
                break;
            case 'prolongePret_ok':
                break;
            }
        },
        
        formatProlonge : function(inValue, rowId, cellId, cellField) {	
			if ( (this.datasLoan[rowId].is_self_renew.is_self_renew == 1) && parseInt(dojoConfig.bibloto.appParams.checkout_activate) ) {
				var prolonge_button = new Button({ 
					label: this.datasLoan[rowId].loan_back_date  + '<br>Prolonger',
					id: 'loan_back_date' + this.datasLoan[rowId].cb,
					className: 'prolonge_button',
					title: 'Prolonger le prêt',
					onClick : lang.hitch(this, this.prolonge, this.datasLoan[rowId].cb),
				});
				prolonge_button._destroyOnRemove = true;
				return prolonge_button;
			}
			return inValue;
        },

        prolonge : function(cb) {
        	topic.publish('loanContainer', 'prolonge', cb);
        },
        
        styleRow : function(row) {
			  var item = this.dataGrid.getItem(row.index);
		      if (item) {
		         var pret_retard = this.dataGrid.store.getValue(item, "pret_retard", null);
		         if(pret_retard == 1) {
			         row.customClasses = "pret_retard";
		        	// row.customStyles += "background: red;";
		         }
		      }
		      this.dataGrid.focus.styleRow(row);
		      this.dataGrid.edit.styleRow(row);	  
        },
        
        handleEvents : function(evtType, evtArgs) {        
            switch(evtType) {
            /**
             * pret evt recu
             */
            case 'explLent':
                this.antivol_level = 0;
                this.addToStore(evtArgs.response, keyboard_cb_enter);
                //console.log(evtArgs.response);
                if (dojoConfig.bibloto.appParams.rfid_activate == 1 && dojoConfig.bibloto.appParams.rfid_security_activate && evtArgs.response.expl_cb != keyboard_cb_enter) {
                    init_rfid_antivol_all_flag = 1;
                    init_rfid_antivol_all_level = 0;
                }
                break;
            case 'explBack':
                this.antivol_level = 1;
                this.popFromStore(evtArgs.response);
                if (dojoConfig.bibloto.appParams.rfid_activate == 1 && dojoConfig.bibloto.appParams.rfid_security_activate && evtArgs.response.expl_cb != keyboard_cb_enter) {
                    init_rfid_antivol_all_flag = 1;
                    init_rfid_antivol_all_level = 1;
                }
                break;
            case 'prolongePret_ok':
                break;
            }
        },

        /**
         * Ajout d'un pret au store de pret
         */
        addToStore : function(datas) {
            if (datas.status == 1) {
				//Gestion de l'impression de ticket'
				if(dojoConfig.printer_id){
					switch(parseInt(dojoConfig.bibloto.appParams.printer_activate)){
						case 1:
							this.print(datas);
							break;
						case 2:
							topic.publish('alertZone', 'showPopup', lang.hitch(this, this.print, datas));
							break;
					}
				}
                var newItm = {
                    title : datas.icondoc + datas.title,
                    loan_date : this.getCurrDate(),
                    loan_back_date : datas.due_date,
                    cb : datas.expl_cb,
                    'is_self_renew' : '',
                };
                this.loanStore.newItem(newItm);
                this.loanStore.save();
            	this.structure[0].name = "Prêts: <span>(" + this.loanStore.objectStore.data.length + ")</span>";
            	this.dataGrid.set('structure',  this.structure);   
            }
        },

        /**
         * Fonction appelée lorsqu'un exemplaire qui était emprunté est rendu
         */
        popFromStore : function(datas) {

            if (this.loanStore.objectStore.query({
                cb : datas.expl_cb
            }).length > 0) {
                var idToDelete = this.loanStore.objectStore.query({cb : datas.expl_cb})[0].id;
                this.loanStore.objectStore.remove(idToDelete);
            }
            this.loanStore.save();
        	this.structure[0].name = "Prêts: <span>(" + this.loanStore.objectStore.data.length + ")</span>";
        	this.dataGrid.set('structure',  this.structure);    	
        },

        /**
         * Récuperation de la date courante au format jj/mm/aaaa
         */
        getCurrDate : function() {
            var today = new Date();
            var dd = today.getDate();
            var mm = today.getMonth() + 1;

            var yyyy = today.getFullYear();
            if (dd < 10) {
                dd = '0' + dd;
            }
            if (mm < 10) {
                mm = '0' + mm;
            }
            return dd + '/' + mm + '/' + yyyy;
        },
        
        print : function(expl) {
            
			var emprLoanPromise = dojoConfig.bibloto.jsonRpcServer.pmbesSelfServices_get_loans_printer_template(dojoConfig.bibloto.readerDatas.emprCb, expl.expl_cb);
			emprLoanPromise.addCallback(lang.hitch(this, function(tpl) {
				var printer_id = dojoConfig.printer_id;
	         	var raspberry_ip = '';
				
	            var temp = dojoConfig.bibloto.appParams.printer_name.split('@');
				raspberry_ip = temp[1];
	
				//On envoie l'impression
				var 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
	                    }
	                )
	            );
            }));
        },
    });
});
