var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var uniflash;
(function (uniflash) {
    var DSLprfImpl = (function (_super) {
        __extends(DSLprfImpl, _super);
        function DSLprfImpl(ds, $q, $rootScope, $log, ticAlerts, ufSession, ufPrograms, ufPropertiesValue, ufAgentInstallDialog, ufPreferencesSrv, ufContext, ufTargetConfig, ufConsole, x2js) {
            _super.call(this, ds, $q, $rootScope, $log, ticAlerts, ufSession, ufPrograms, ufPropertiesValue, ufAgentInstallDialog, ufPreferencesSrv, ufContext, ufTargetConfig, ufConsole, x2js);
            this.ds = ds;
            this.$q = $q;
            this.$rootScope = $rootScope;
            this.$log = $log;
            this.ticAlerts = ticAlerts;
            this.ufSession = ufSession;
            this.ufPrograms = ufPrograms;
            this.ufPropertiesValue = ufPropertiesValue;
            this.ufAgentInstallDialog = ufAgentInstallDialog;
            this.ufPreferencesSrv = ufPreferencesSrv;
            this.ufContext = ufContext;
            this.ufTargetConfig = ufTargetConfig;
            this.ufConsole = ufConsole;
            this.x2js = x2js;
        }
        DSLprfImpl.matches = function (partnum) {
            for (var _i = 0, _a = DSLprfImpl.deviceFilter; _i < _a.length; _i++) {
                var filter = _a[_i];
                if (filter.test(partnum)) {
                    return true;
                }
            }
            //nothing matches
            return false;
        };
        // use a ccxml that can allow us to detect for unlock and to perform a mass erase on the icepick core
        DSLprfImpl.prototype.modifyCCXML = function () {
            var connection = this.ufSession.getConnectionXMLFile();
            var ccxmlName = "";
            if (connection === "TIXDS110_Connection") {
                ccxmlName = "cc13xx_cc26xx_2pin_cJTAG_XDS110.ccxml";
            }
            else if (connection === "TIXDS100v3_Dot7_Connection") {
                ccxmlName = "cc13xx_cc26xx_2pin_cJTAG_XDS100v3.ccxml";
            }
            else if (connection === "TIXDS2XXUSB_Connection" || connection === "TIXDS2XXUSB_onboard_Connection") {
                ccxmlName = "cc13xx_cc26xx_2pin_cJTAG_XDS200.ccxml";
            }
            return this.ufTargetConfig.getFileContent("ccs_base/arm/" + ccxmlName);
        };
        DSLprfImpl.prototype.handleLockedScenario = function () {
            var _this = this;
            var m3CorePath;
            var customDsConfigObj;
            var modifiedCCXML;
            return this.modifyCCXML()
                .then(function (ccxmlContent) {
                var deferred = _this.$q.defer();
                if (ccxmlContent instanceof Blob) {
                    var reader = new FileReader();
                    reader.onload = function (readContent) {
                        modifiedCCXML = readContent.currentTarget.result;
                        deferred.resolve();
                    };
                    reader.readAsText(ccxmlContent);
                    return deferred.promise;
                }
                else {
                    modifiedCCXML = ccxmlContent;
                }
            })
                .then(function () {
                return _this.deconfigureDS(true);
            })
                .then(function () {
                return _this.configureDS(modifiedCCXML, 'uniflash_modified_temp.ccxml');
            })
                .then(function (dsconfigObj) {
                // find icepick path and connect to icepick
                customDsConfigObj = dsconfigObj;
                m3CorePath = dsconfigObj.configData.cores[0];
                return _this.connectToCore(DSLprfImpl.icePickName, dsconfigObj, true);
            })
                .then(function (core) {
                if (core) {
                    return core.expressions.evaluate('IP_TAP_CNTL_0')
                        .then(function (registerVal) {
                        _this.$log.debug('IP_TAP_CNTL_0 = ' + registerVal.value);
                        var isLocked = !((parseInt(registerVal.value, 16) >> 1) & 1);
                        _this.$log.debug('isLocked = ' + isLocked);
                        return isLocked;
                    });
                }
                else {
                    throw { message: 'Cannot connect to IcePick.' };
                }
            })
                .then(function (isLocked) {
                if (isLocked) {
                    // reject need to be catched
                    var modifiedCCXML2_1 = modifiedCCXML;
                    return _this.ticAlerts.showConfirm('This device is locked', 'Do you want to do a mass erase to unlock it? The flash memory on this device will be wiped.')
                        .then(function () {
                        return _this.deconfigureDS(true);
                    })
                        .then(function () {
                        return _this.configureDS(modifiedCCXML2_1, 'uniflash_modified_temp.ccxml');
                    })
                        .then(function (dsconfigObj) {
                        // find icepick path and connect to icepick
                        customDsConfigObj = dsconfigObj;
                        m3CorePath = dsconfigObj.configData.cores[0];
                        return _this.massErase(m3CorePath, customDsConfigObj);
                    });
                }
            })
                .finally(function () {
                return _this.deconfigureDS(true);
            });
        };
        DSLprfImpl.prototype.massErase = function (path, dsConfigObj) {
            //run gel expression to massErase on cortex m3
            this.$log.debug('running massErase()');
            return this.getCore(path, dsConfigObj)
                .then(function (core) {
                return core.expressions.evaluate('MassErase()');
            });
        };
        DSLprfImpl.prototype.completeWorkflowAction = function (mainAction, coreName, optionObj) {
            var _this = this;
            this.$rootScope.$emit('ds.opStarted');
            var curCore;
            var handleLockIfNecessary = (optionObj && optionObj.DoNotHandleUnlock) ? this.$q.resolve('') : this.handleLockedScenario();
            return handleLockIfNecessary
                .then(function () {
                return _this.configureDS(_this.ufSession.getCCXML(), 'uniflash_temp.ccxml');
            })
                .then(function (ret) {
                return _this.connectToCore(coreName, ret);
            })
                .then(function (core) {
                if (core && mainAction) {
                    curCore = core;
                    return core.targetState.halt()
                        .catch(function (e) {
                        if (e.message !== 'Target is not running') {
                            _this.$log.error('Halt target failed: ' + e.message);
                            throw e;
                        }
                    });
                }
            })
                .then(function () {
                if (curCore) {
                    return mainAction(curCore);
                }
            })
                .catch(function (error) {
                if (error !== 'backdrop click' && error !== 'No' &&
                    !(error instanceof ti_common.CancelError)) {
                    return _this.ticAlerts.showError(error.message);
                }
            })
                .finally(function () {
                return _this.$q(function (resolve) {
                    if (curCore) {
                        resolve(curCore.settings.get([])
                            .then(function (ret) {
                            _this.ufPropertiesValue.updateFromDS(ret.nameValueMap, _this.ufContext.getCurrentCore().name, 'lprf');
                        }));
                    }
                    else {
                        resolve();
                    }
                })
                    .then(function () {
                    if (optionObj && (optionObj.connect === false)) {
                        // don't need to run target if we are not connecting to the target (ie; NCOperation)
                        return;
                    }
                    if (curCore && optionObj && optionObj.runAfterOp) {
                        return curCore.targetState.run(1).catch(function (e) {
                            if (e) {
                                _this.$log.error('completeWorkflowAction curCore.targetState.run(1) ' + JSON.stringify(e));
                            }
                        });
                    }
                })
                    .then(function () {
                    if (optionObj && (optionObj.connect === false || optionObj.disconnect === false)) {
                        // don't need to disconnect if we did not connect (ie; NCOperation), or if we don't want to disconnect
                        return;
                    }
                    if (_this.ufPreferencesSrv.get('Auto Disconnect')) {
                        return _this.disconnectAllCores().catch(function (e) {
                            if (e) {
                                _this.$log.error('completeWorkflowAction this.disconnectAllCores() ' + JSON.stringify(e));
                            }
                        });
                    }
                })
                    .finally(function () {
                    _this.$rootScope.$emit('ds.opFinished');
                });
            });
        };
        DSLprfImpl.deviceFilter = [/cc13\d\d/i, /cc26\d\d/i, /cc2538/i];
        DSLprfImpl.icePickName = 'IcePick_C';
        return DSLprfImpl;
    }(uniflash.DSDefaultImpl));
    uniflash.DSLprfImpl = DSLprfImpl;
})(uniflash || (uniflash = {}));
