/*global TICloudAgent*/
var uniflash;
(function (uniflash) {
    var target_config;
    (function (target_config) {
        'use strict';
        var TargetConfig = (function () {
            function TargetConfig(ticAgentAPI, $q) {
                this.ticAgentAPI = ticAgentAPI;
                this.$q = $q;
                this.parsedConfigurables = [];
            }
            TargetConfig.prototype.getLaunchPadInfo = function () {
                return this.ticAgentAPI.getLpListJson()
                    .then(function (response) {
                    return JSON.parse(response.data);
                });
            };
            TargetConfig.prototype.getLaunchPads = function () {
                return this.getLaunchPadInfo().then(function (data) {
                    return data.launchpads;
                });
            };
            TargetConfig.prototype.getConfigInfo = function () {
                if (!this.cachedPromise) {
                    this.cachedPromise = this.ticAgentAPI.getConfigInfo(TICloudAgent.getOS())
                        .then(function (response) {
                        return JSON.parse(response.data);
                    });
                }
                return this.cachedPromise;
            };
            TargetConfig.prototype.getDevices = function () {
                return this.getConfigInfo()
                    .then(function (data) {
                    return data.devices;
                });
            };
            TargetConfig.prototype.getDevice = function (deviceXMLFile) {
                return this.getDevices()
                    .then(function (devices) {
                    return _.find(devices, {
                        xmlFile: deviceXMLFile
                    });
                });
            };
            TargetConfig.prototype.getConnection = function (connectionIndices, connectionXMLFile) {
                return this.getConnections(connectionIndices)
                    .then(function (connections) {
                    return _.find(connections, {
                        xmlFile: connectionXMLFile
                    });
                });
            };
            TargetConfig.prototype.getConnectionWithXML = function (connectionXMLFile) {
                return this.getConnectionList()
                    .then(function (connections) {
                    return _.find(connections, {
                        xmlFile: connectionXMLFile
                    });
                });
            };
            TargetConfig.prototype.getConnections = function (connectionIndices) {
                return this.getConfigInfo()
                    .then(function (data) {
                    var connections = _.map(connectionIndices, function (connectionIndex) {
                        return data.connections[connectionIndex];
                    });
                    return connections;
                });
            };
            TargetConfig.prototype.getConnectionList = function () {
                return this.getConfigInfo().then(function (data) {
                    return data.connections;
                });
            };
            TargetConfig.prototype.getConnectionIndex = function (curConnection) {
                return this.getConnectionList().then(function (connections) {
                    return _.findIndex(connections, function (connection) {
                        return (connection.xmlFile === curConnection.xmlFile);
                    });
                });
            };
            TargetConfig.prototype.queryConfig = function (ccxmlFileContents) {
                return this.ticAgentAPI.queryConfig(ccxmlFileContents, TICloudAgent.getOS())
                    .then(function (response) {
                    var configResult = JSON.parse(response.data);
                    // filter cores that should not be shown in uniflash (see UNIFLASH-421)
                    configResult.debuggableCores = _.filter(configResult.cores, function (core) {
                        return core.isa.indexOf("cs_child") === -1 && core.isa.indexOf("AJSM") === -1;
                    });
                    configResult.nondebuggableCores = _.filter(configResult.cores, function (core) {
                        return core.isa.match(/TMS192C.*/) || core.isa.indexOf("cs_child") === 1 || core.isa.indexOf("AJSM") === 1;
                    });
                    configResult.cores = _.filter(configResult.cores, function (core) {
                        return !core.isa.match(/TMS192C.*/) && core.isa.indexOf("cs_child") === -1 && core.isa.indexOf("AJSM") === -1;
                    });
                    return configResult;
                });
            };
            TargetConfig.prototype.resetConfigurables = function () {
                this.configurables = undefined;
            };
            TargetConfig.prototype.getConfigurables = function (deviceXMLFile, connectionXMLFile) {
                var _this = this;
                if (!this.configurables) {
                    return this.ticAgentAPI.getConfigurables(TICloudAgent.getOS(), connectionXMLFile, deviceXMLFile)
                        .then(function (configurablesRes) {
                        _this.configurables = JSON.parse(configurablesRes.data);
                        _this.parsedConfigurables = [];
                        _this.parseConfigurables();
                    });
                }
                else {
                    return this.$q.resolve();
                }
            };
            TargetConfig.prototype.parseConfigurables = function () {
                var _this = this;
                // we will only look at the first connection configurables for now
                _.each(this.configurables.connections[0].configurables, function (curConfigurable) {
                    if (curConfigurable.property) {
                        _this.parseCurConfigurable(curConfigurable.property.$, curConfigurable.property.choice, false);
                    }
                });
            };
            TargetConfig.prototype.parseCurConfigurable = function (curConfigurable, curChoices, hidden, parent, choiceValue) {
                var _this = this;
                if (curConfigurable.Type === 'hiddenfield') {
                    return;
                }
                var id, name;
                if (curConfigurable.desc) {
                    name = curConfigurable.desc;
                }
                else if (curConfigurable.Name) {
                    name = curConfigurable.Name;
                }
                if (curConfigurable.id) {
                    id = curConfigurable.id;
                }
                else if (curConfigurable.ID) {
                    id = curConfigurable.ID;
                }
                else {
                    id = name;
                }
                // hide filepathfields for now since we can't handle browsing for cloud version yet.
                if (!hidden && (curConfigurable.Type === 'hiddenfield')) {
                    hidden = true;
                }
                var curParsedConfigurable = {
                    'id': id,
                    'name': name,
                    'type': curConfigurable.Type,
                    'value': curConfigurable.Value,
                    'choices': [],
                    'hidden': hidden,
                    'extensions': curConfigurable.Extensions ? curConfigurable.Extensions : '',
                    'rules': [],
                    'children': [],
                    'configurableObj': curConfigurable
                };
                // if this is a child property, add some rule information into the parent
                if (parent) {
                    curParsedConfigurable.id = parent.id + '_' + choiceValue + '_' + curParsedConfigurable.id;
                    parent.rules.push({ 'id': curParsedConfigurable.id, 'value': choiceValue });
                    parent.children.push(curParsedConfigurable);
                    curParsedConfigurable.hidden = parent.hidden || !(parent.value === choiceValue);
                }
                this.parsedConfigurables.push(curParsedConfigurable);
                if (curParsedConfigurable.type === 'choicelist') {
                    var curValueObj = curChoices[parseInt(curConfigurable.Value)].$;
                    if (curValueObj.Name) {
                        curParsedConfigurable.value = curValueObj.Name;
                    }
                    else {
                        curParsedConfigurable.value = curValueObj.value;
                    }
                    var choices_1 = [];
                    _.each(curChoices, function (curChoice) {
                        var choiceValue;
                        if (curChoice.$.Name) {
                            choiceValue = curChoice.$.Name;
                        }
                        else {
                            choiceValue = curChoice.$.value;
                        }
                        choices_1.push(choiceValue);
                        // parse properties into the choice
                        if (curChoice.property) {
                            _.each(curChoice.property, function (curProp) {
                                _this.parseCurConfigurable(curProp.$, curProp.choice, hidden, curParsedConfigurable, choiceValue);
                            });
                        }
                    });
                    curParsedConfigurable.choices = choices_1;
                }
            };
            TargetConfig.prototype.getConfigurablesList = function () {
                return this.configurables;
            };
            TargetConfig.prototype.getParsedConfigurablesList = function () {
                return this.parsedConfigurables;
            };
            TargetConfig.prototype.setConfigurablesValue = function (id, value) {
                var matchedConfigurable = _.find(this.parsedConfigurables, function (curConfigurables) {
                    return curConfigurables.id === id;
                });
                if (matchedConfigurable) {
                    matchedConfigurable.value = value;
                }
            };
            TargetConfig.prototype.getConfigurableObj = function (id) {
                // find the property with the given id, and get the current value
                var matchedConfigurable = _.find(this.parsedConfigurables, function (curConfigurables) {
                    return curConfigurables.id === id;
                });
                if (matchedConfigurable) {
                    return matchedConfigurable;
                }
                return;
            };
            TargetConfig.prototype.applyConfigurablesValues = function () {
                _.each(this.parsedConfigurables, function (curConfigurables) {
                    if (curConfigurables.type === 'choicelist') {
                        var index = _.indexOf(curConfigurables.choices, curConfigurables.value);
                        curConfigurables.configurableObj.Value = index.toString();
                    }
                    else {
                        curConfigurables.configurableObj.Value = curConfigurables.value;
                    }
                });
            };
            TargetConfig.prototype.configurableValueChanged = function (configurable) {
                var _this = this;
                _.each(configurable.rules, function (curRule) {
                    var hidden = ((curRule.value !== configurable.value) || configurable.hidden);
                    var childConfigurable = _this.getConfigurableObj(curRule.id);
                    _this.setHidden(childConfigurable, hidden);
                });
            };
            TargetConfig.prototype.setHidden = function (configurable, hidden) {
                if (configurable.type === 'hiddenfield') {
                    return;
                }
                configurable.hidden = hidden;
                this.configurableValueChanged(configurable);
            };
            TargetConfig.prototype.createCCXML = function (deviceXMLFile, connectionXMLFile, lp) {
                var _this = this;
                this.applyConfigurablesValues();
                var promise = this.$q.when();
                // temporary workaround to set the 2pin JTAG setting for F280049C LaunchPads
                if (lp && (deviceXMLFile == "f280049c") && (connectionXMLFile == "TIXDS110_Connection")) {
                    if (!this.configurables) {
                        promise = this.getConfigurables(deviceXMLFile, connectionXMLFile);
                    }
                    promise = promise.then(function () {
                        var configurables = _this.configurables.connections[0].configurables;
                        for (var i = 0; i < configurables.length; i++) {
                            if (configurables[i].property && configurables[i].property.$ && configurables[i].property.$.id === 'SWD Mode Settings') {
                                configurables[i].property.$.Value = 4;
                                break;
                            }
                        }
                    });
                }
                return promise.then(function () {
                    var configurablesStr = JSON.stringify(_this.configurables);
                    return _this.ticAgentAPI.getConfig(TICloudAgent.getOS(), connectionXMLFile, deviceXMLFile, configurablesStr)
                        .then(function (response) {
                        _this.resetConfigurables();
                        return response.data;
                    });
                });
            };
            TargetConfig.prototype.getFileContent = function (path) {
                return this.ticAgentAPI.getFileContent(TICloudAgent.getOS(), path)
                    .then(function (response) {
                    return response.data;
                });
            };
            TargetConfig.$inject = ['ticAgentAPI', '$q'];
            return TargetConfig;
        }());
        target_config.TargetConfig = TargetConfig;
        angular.module('uniflash').service('ufTargetConfig', TargetConfig);
    })(target_config = uniflash.target_config || (uniflash.target_config = {}));
})(uniflash || (uniflash = {}));
