(function () {

    'use strict';

    angular.module('uniflash').directive('ufConfigCcxml', ufConfigCcxml);

    function ufConfigCcxml() {
        var directive = {
            restrict: 'E',
            controller: ConfigCcxml,
            controllerAs: 'vm',
            templateUrl: 'target_setup/config_ccxml.html',
            scope: {},
        };
        return directive;
    }


    class ConfigCcxml {
        static $inject = ['$log', '$state', 'ticAlerts', 'ticFileDialogs', 'ufTargetConfig', 'ufProgramProviders', 'ufSession'];
        private show: boolean = true;
        private selectedCcxml: ti_common.file.File;

        constructor(private $log, private $state, private ticAlerts, private ticFileDialogs, private ufTargetConfig, private ufProgramProviders, private ufSession) { }

        getIcon() {
            return this.ufProgramProviders.icon;
        }

        selectCcxmlFile() {
            return this.ticFileDialogs.openFile('Select Target Configuration File', '.ccxml', 'Target Configurations')
                .then((selections: ti_common.file.File[]) => {
                    this.selectedCcxml = selections[0];
                }).catch((err) => {
                    this.$log.error(err);
                });
        }

        private getFileName(filePath) {
            let idxOfSlash = filePath.lastIndexOf('/');
            idxOfSlash = (idxOfSlash < 0) ? 0 : idxOfSlash;
            let idxOfDot = filePath.lastIndexOf('.');
            idxOfDot = (idxOfDot < 0) ? filePath.length : idxOfDot;
            if (idxOfDot < idxOfSlash) {
                throw 'Bad file path: ' + filePath;
            }

            let ret = filePath.substring(idxOfSlash + 1, idxOfDot);
            return ret;
        }

        parseCcxml(ccxmlContent) {
            return this.ufTargetConfig.queryConfig(ccxmlContent)
                .then((queryConfig: uniflash.target_config.QueryConfigResult) => {
                    // set our internal data;
                    return {
                        device: this.getFileName(queryConfig.deviceXMLFile),
                        connection: this.getFileName(queryConfig.connectionXMLFile)
                    };
                });
        }

        startSession() {
            if (this.selectedCcxml) {
                let contents;
                return this.selectedCcxml.getContents()
                    .then((data) => {
                        contents = data;
                        return this.parseCcxml(data);
                    })
                    .then((ret) => {
                        return this.ufSession.newFromCCXML(ret.device, ret.connection, contents)
                            .then(() => {
                                this.$state.go('main.Program', {
                                    deviceXMLFile: ret.device,
                                    connectionXMLFile: ret.connection
                                });
                            })
                    })
                    .catch((e) => {
                        let msg = e.data || e;
                        this.ticAlerts.showError('Failed to launch session from ccxml file: ' + msg);
                    });
            }
        }
    }
})();