/// <reference path="http://localhost/IndustrialDashboard/Scripts/IndustrialDashboard.js" />
define(["app", "js/ih-runtime-lib", "underscore"], function (app, IHRuntime) {
    var ihlib = function IHLib(opt){
        try {
            this.options = {
                screenId: null,
                user: null, 
                timezone: null, 
            }; 

            this.options = _.extend(this.options, ((_.isObject(opt)) ? opt : (_.isString(opt)) ? { screenId: opt } : {}));
        } catch (error) { console.log("Error while trying to instance new IHLib. Error: [" + error.toString() + "]") }
    };

    function callAPI(data, callback) {
        try {
            var that = this;
            $.ajax(app.foldersRoot + "/app/custom-screens/screen-builder/api.aspx", {
                type: 'POST',
                data: data,
                success: function (res) {
                    if (callback && _.isFunction(callback)) {
                        callback.call(that, true, res);
                    }
                },
                error: function (res) {
                    console.log("error");
                    if (callback && _.isFunction(callback)) {
                        callback.call(that, false, res);
                    }
                }
            });
        } catch (error) {
            console.log("Error while calling API. Error: " + error.toString());
        }
    }; 

    ihlib.prototype.getUser = function () {
        return this.options.user;
    }; 

    ihlib.prototype.getTimezone = function () {
        return this.options.timezone; 
    }; 

    ihlib.prototype.getScreenId = function () {
        return this.options.screenId; 
    };

    ihlib.prototype.getTagValue = function (tagNames, timezone, callback) {
        var code = "sb-screen-" + this.options.screenId.toString(); 
        var subcode = null; 

        //optional parameter timezone
        var timezone = _.isString(timezone) ? timezone : null;
        var callback = _.isFunction(callback) ? callback : _.isFunction(timezone) ? timezone : null; 

        IHRuntime.getLastTagValue(tagNames, code, subcode, false, timezone, callback);
    };

    ihlib.prototype.getTagValueRange = function (tagNames, from, to, timezone, callback) {
        //optional parameter timezone
        var timezone = _.isString(timezone) ? timezone : null;
        var callback = _.isFunction(callback) ? callback : _.isFunction(timezone) ? timezone : null;

        IHRuntime.getTagValues(tagNames, from, to, timezone, callback);
    };

    ihlib.prototype.sendAgentCommand = function (agentName, commandText, callback) {
        /// <summary>
        /// Send command to agent
        /// </summary>  
        /// <param name="agentName" type="Varchar">Name or alias of agent.</param>  
        /// <param name="commandText" type="Varchar">Command text.</param>  
        /// <param name="callback/options" type="Function/Object">Callback or object to extend options.</param>
        var that = this;

        var options = {
            async: true,
            callback: function () { },
        };

        if (_.isFunction(callback)) { options.callback = callback; }
        else if (_.isObject(callback)) { options = _.extend(options, callback) };

        var QP = new Core.Database.QueryParameters();
        QP.Add("agentName", "VARCHAR", agentName);
        QP.Add("commandText", "VARCHAR", commandText);

        var status = false;
        Core.Json.CallProcedure(app.DatabaseNames.System + ".SYSTEM.IHLib_SendAgentCommand", QP, {
            onSuccess: function (data) {
                var dbStatus = data && data.Table && data.Table.length > 0 && data.Table[0].Status ? data.Table[0].Status : 'FAILED';

                status = (dbStatus == "OK") ? true : false; 

                if (options.callback != null && _.isFunction(options.callback))
                    options.callback.call(that, status);
            },
            Async: options.async,
            Secured: true,
        }, app.ConnectionStrings.app);

        if (!options.async) return status;
    }; 

    ihlib.prototype.getServerCurrentDatetime = function () {
        app.models.navBarClock.syncWithServer({ async: false });
        return app.models.navBarClock.get("date");
    };

    ihlib.prototype.readXML = function (name, global, callback) {
        try {
            var that = this;
            var response = null; 

            callAPI({ screenId: this.options.screenId.toString(), action: "READXML", filename: name, global: global }, function (status, res) {
                if (status == true) {
                    response = res.Data.Contents; 
                }

                if (callback && _.isFunction(callback))
                    callback.call(that, status, response);
            });
        } catch (error) { console.log("Error while trying to read XML. Error: " + error.toString()); }
    };

    ihlib.prototype.writeXML = function (name, contents, global, callback) {
        try {
            var that = this;
            var response = null;

            callAPI({ screenId: this.options.screenId.toString(), action: "WRITEXML", filename: name, contents: contents, global: global }, function (status, res) {
                if (status == true) {
                    response = res.Data.Contents;
                }

                if (callback && _.isFunction(callback))
                    callback.call(that, status, response);
            });
        } catch (error) { console.log("Error while trying to write XML. Error: " + error.toString()); }
    };

    ihlib.prototype.parseXML = function (contents) {
        var parseXml, xmlDoc = null;

        if (window.DOMParser) {
            xmlDoc = (new window.DOMParser()).parseFromString(contents, "text/xml");
        } else if (typeof window.ActiveXObject != "undefined" && new window.ActiveXObject("Microsoft.XMLDOM")) {
            xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM");
            xmlDoc.async = "false";
            xmlDoc.loadXML(contents);
        }

        return xmlDoc; 
    }

    return ihlib; 
});