// +-------------------------------------------------+
// © 2002-2004 PMB Services / www.sigb.net pmb@sigb.net et contributeurs (voir www.sigb.net)
// +-------------------------------------------------+
// $Id: connector.js,v 1.9 2022/05/11 15:14:24 rtigero Exp $

define(["dojo/_base/declare", 'dojo/rpc/JsonService', "dojo/topic", "dojo/_base/lang", "app/urlDialog", "dojo/on", 'dojo/request/xhr', "dojo/Deferred", 'dojo/io-query'], function(declare, JsonService, topic, lang, urlDialog, on, xhr, Deferred, ioQuery) {
	return declare(null, {
		deferred: null,
		params: null,
		code: "",
		constructor: function() {
			this.code = ioQuery.queryToObject(decodeURIComponent(dojo.doc.location.search.slice(1))).code;
			xhr("config.json", {
				handleAs: "json"
			}).then(lang.hitch(this, function(data) {
				if (!data['PmbSources'] || data['PmbSources'].length == 0) {
					this.instanciateDialog("PmbSources array not found in config.json");
				} else {
					if (!data['PmbSources'][this.code]) {
						for (key in data['PmbSources']) {
							biblotoConnectorUrl = data['PmbSources'][key];
							// on prend la premiere source
							break;
						}
					} else {
						biblotoConnectorUrl = data['PmbSources'][this.code];
					}
					if (biblotoConnectorUrl == "") {
						this.instanciateDialog("No source url in config.json");
					} else {
						this.testConnectorUrl();
					}
				}
			}), lang.hitch(this, function(err) {
				this.instanciateDialog("config.json not found or invalid json format");
			}));
		},

		instanciateWs: function() {
			dojoConfig.bibloto = {};
			dojoConfig.bibloto.appParams = this.params;
			if (dojoConfig.bibloto.appParams.auth_login && dojoConfig.bibloto.appParams.auth_password) {
				dojoConfig.bibloto.appParams.pmb_ws_url += '&auth_user=' + dojoConfig.bibloto.appParams.auth_login + '&auth_pw=' + dojoConfig.bibloto.appParams.auth_password;
			}
			dojoConfig.bibloto.jsonRpcServer = new JsonService(dojoConfig.bibloto.appParams.pmb_ws_url);
			if (dojoConfig.bibloto.jsonRpcServer.serviceUrl != dojoConfig.bibloto.appParams.pmb_ws_url) {
				dojoConfig.bibloto.jsonRpcServer.serviceUrl = dojoConfig.bibloto.appParams.pmb_ws_url;
			}
			if (dojoConfig.bibloto.jsonRpcServer) {
				this.testWs();
			} else {
				this.resetValues();
				this.instanciateDialog("Problème de connexion avec l\'url fournie " + biblotoConnectorUrl);
			}
		},

		testConnectorUrl: function() {
			xhr(biblotoConnectorUrl, {
				handleAs: "json",
			}).then(lang.hitch(this, function(params) {
				if (params && params.pmb_ws_url) {
					this.params = params;
					this.instanciateWs();
				} else {
					this.resetValues();
					this.instanciateDialog("Problème de paramétrage du connecteur sortant: " + biblotoConnectorUrl);
				}

			}), lang.hitch(this, function(err) {
				this.resetValues();
				this.instanciateDialog("Impossible de récupérer les paramètres du connecteur: " + biblotoConnectorUrl);
			}));
		},

		testWs: function() {
			var state = true;
			if (dojoConfig.bibloto.appParams.checkin_activate * 1) {
				if (typeof dojoConfig.bibloto.jsonRpcServer.pmbesSelfServices_self_checkin != "function") {
					state = false;
				}
			}
			if (dojoConfig.bibloto.appParams.checkout_activate * 1) {
				if (typeof dojoConfig.bibloto.jsonRpcServer.pmbesSelfServices_self_checkout_bibloto != "function" ||
					typeof dojoConfig.bibloto.jsonRpcServer.pmbesSelfServices_self_del_temp_pret != "function") {
					state = false;
				}
			}
			if (dojoConfig.bibloto.appParams.trombinoscope_enabled * 1) {
				if (typeof dojoConfig.bibloto.jsonRpcServer.pmbesEmpr_bibloto_empr_list != "function") {
					state = false;
				}
			}
			if (parseInt(dojoConfig.bibloto.appParams.printer_activate) > 0) {
				if (typeof dojoConfig.bibloto.jsonRpcServer.pmbesSelfServices_get_loans_printer_template != "function") {
					state = false;
				}
			}
			if (state == true) {
				this.testMapping();
			} else {
				this.resetValues();
				this.instanciateDialog("Problème de paramétrage des autorisations des fonctions du webservice: " + biblotoConnectorUrl);
			}
		},

		resetValues: function() {
			this.params = null;
			dojoConfig.bibloto = {};
			window.localStorage.removeItem('biblotoConnectorUrl');
		},

		instanciateDialog: function(message) {
			new urlDialog(message).deferred.then(lang.hitch(this, this.testConnectorUrl));
		},

		testMapping: function() {
			xhr("mapping.csv", {
				handleAs: "text",
			}).then(
				lang.hitch(this,
					function(mapping) {
						dojoConfig.bibloto.mapping = this.csvToObj(mapping);
						topic.publish('connector', 'gotUrl');
					}
				),
				lang.hitch(this,
					function(err) {
						topic.publish('connector', 'gotUrl');
					}
				)
			);

		},

		csvToObj: function(csvString) {

			var sep = ';';
			var lines = csvString.replace(/\r/g, '').split(/\n/);
			var result = new Object();
			//var headers=lines[0].split(sep);
			for (var i = 1; i < lines.length; i++) {
				var currentline = lines[i].split(sep);
				result[currentline[0]] = currentline[1];
			}
			return result;
		},

	});
});
