angular.module("app").directive("instrumentDetails", function ($rootScope, $timeout, $sce, SQConstants, SQEvents, UniqueIdGenerator, AppService, BackendService) {
    return {
        restrict: 'E',
        replace: true,
        templateUrl: "../app/directives/instrumentDetails/instrumentDetails.html",
        scope: {
            instrument: '=',
            instance: '=',
            disabled: '=', //disables all fields
            currentAction: '=', //'Add' / 'Edit'
            legend: '@',
            commissionSettings: '=', //show/hide commission settings        
            massEdit: '@'    
        },
        link: function (scope, element, attrs) {
            function initCommissionSettings() {
                BackendService.sendRequest('constants/listCommissionMethods', null, function (result) {
                    loadToArray(scope.commissionMethods, result.methods);
    
                    updateCommissionSettings();
                });
            }

            function updateCommissionSettings() {
                disableCommissionsWatch = true;
              
                if (scope.commPGInstance.setSettings) {
                    scope.commPGInstance.setSettings(parseMethodSettings(xmlToObject(scope.instrument.commissions).find("Method")[0]));
                }

                disableCommissionsWatch = false;
            }

            function updateInfoLabel(){
                scope.infoText = '';
                scope.instrumentUsed = false;
            }

            function isInstrumentUsed(instrument){
                var data = SQConstants.getConstants().data;
                if(!data) return false;

                for(var i=0; i<data.length; i++){
                    if(data[i].instrument == instrument) return true;
                }

                return false;
            }

            scope.onBrokerChange = function(){
                scope.brokerProfile = getItem(scope.brokerProfiles, 'id', scope.instrument.broker);
            }
            

            scope.onCommPGChange = function () {
                var newType = scope.commPGInstance.getSelectedType(); //method name
                var xmlDoc = AppService.xmlDoc;

                var xmlConfig = xmlDoc.createElement("Method");
                xmlConfig.setAttribute("type", newType);
                xmlConfig.setAttribute("use", true);
                scope.commPGInstance.setPropertyValues(xmlDoc, xmlConfig);
                scope.instrument.commissions = xmlToString(xmlConfig);
            }

            scope.getTickSizeStep = function () {
                switch (scope.instrument.dataType) {
                    case 1:
                        return 0.01;
                    case 2:
                        return 0.1;
                    default:
                        return 0.0001;
                }
            }

            scope.getTickStepStep = function () {
                switch (scope.instrument.dataType) {
                    case 1:
                        return 0.01;
                    case 2:
                        return 0.1;
                    default:
                        return 0.00001;
                }
            }

            scope.getDataTypeLabel = function(){
                var dataType = getItem(scope.dataTypes, 'value', scope.instrument.dataType);
                return dataType ? dataType.name : '';
            }

            scope.getBrokerProfileLabel = function(){
                var brokerProfile = getItem(scope.brokerProfiles, 'id', scope.instrument.broker);
                return brokerProfile ? brokerProfile.name : '';
            }

            function setDefaultValues() {
                switch (scope.instrument.dataType) {
                    case 1:
                        scope.instrument.pointValue = 1;
                        scope.instrument.tickSize = 0.01;
                        scope.instrument.tickStep = 0.01;
                        scope.instrument.defaultSpread = 0;
                        scope.instrument.defaultSlippage = 0;
                        scope.instrument.commissions = defaultCommissions;
                        break;
                    case 2:
                        scope.instrument.pointValue = 1;
                        scope.instrument.tickSize = 0.1;
                        scope.instrument.tickStep = 0.1;
                        scope.instrument.defaultSpread = 0;
                        scope.instrument.defaultSlippage = 0;
                        scope.instrument.commissions = defaultCommissions;
                        break;
                    default:
                        scope.instrument.pointValue = 100000;
                        scope.instrument.tickSize = 0.0001;
                        scope.instrument.tickStep = 0.00001;
                        scope.instrument.defaultSpread = 1;
                        scope.instrument.defaultSlippage = 0;
                        scope.instrument.commissions = defaultCommissions;
                        break;
                }

                scope.instrument.minDistance = 0.0;
                scope.instrument.swap = '<Swap use="false" type="money" long="0" short="0" tripleSwapOn="WEDNESDAY" />';
                scope.instrument.orderSizeMultiplier = 1;
                scope.instrument.orderSizeStep = 1;

                updateCommissionSettings();
            }

            var destroyWatch = scope.$watch('instrument', function (newValue, oldValue) {
                if(newValue.dataType != oldValue.dataType){
                    if (!scope.instrument.dataType && scope.dataTypes.length > 0) {
                        scope.instrument.dataType = scope.dataTypes[0].value;
                    }
                }

                if (newValue.commissions && newValue.commissions != oldValue.commissions && !disableCommissionsWatch) {
                    updateCommissionSettings();
                }

                if(newValue.instrument != oldValue.instrument){
                    updateInfoLabel();
                }
                
                scope.instrument.swap = scope.instrument.swap || "";
            });

            var destroyWatch2 = scope.$watch('currentAction', function (newValue, oldValue) {
                if (scope.currentAction == 'Add') {
                    setDefaultValues();
                }

                updateCommissionSettings();
                updateInfoLabel();
            });

            function onEvent(event, data) {
                if (event == SQEvents.get('BROKERS_CHANGED')) {
                    reloadBrokers();
                }else if (event == SQEvents.get('EXCHANGES_CHANGED')) {
                    scope.exchanges = angular.copy(data);
                } else if (event == SQEvents.get('COUNTRIES_CHANGED')) {
                    scope.countries = angular.copy(data);
                } else if (event == SQEvents.get('SECTORS_CHANGED')) {
                    scope.sectors = angular.copy(data);
                } else if (event == SQEvents.get('DATA_CHANGED')) {
                    updateInfoLabel();
                } else return;

                try { $scope.$digest(); } catch (er) {}
            }

            function reloadBrokers(){
                var brokerProfiles = angular.copy(SQConstants.getConstants().brokers).filter(b=>b.mtUse);
                brokerProfiles.unshift({
                    id:-1,
                    name:'SQ default'
                });
                scope.brokerProfiles = brokerProfiles;
            }

            scope.$on('$destroy', function () {
                destroyWatch();
                destroyWatch2();
                SQEvents.removeListener(listenerId);
                UniqueIdGenerator.removeId(uniqueId);
            })

            var defaultCommissions = "<Method type=\"None\" use=\"true\"><Params/></Method>";
            var disableCommissionsWatch = false;

            scope.commissionMethods = [];
            scope.commPGInstance = {};

            if (scope.commissionSettings) initCommissionSettings();

            scope.dataTypes = angular.copy(SQConstants.getConstants().dataTypes);

            reloadBrokers();
            scope.exchanges = angular.copy(SQConstants.getConstants().exchanges);
            scope.countries = angular.copy(SQConstants.getConstants().countries);
            scope.sectors = angular.copy(SQConstants.getConstants().sectors);
            scope.swapTypes = angular.copy(SQConstants.getConstants().swapTypes);

            scope.infoText = '';

            if (!scope.instrument.dataType && scope.dataTypes.length > 0) {
                scope.instrument.dataType = scope.dataTypes[0].value;
            }

            if (!scope.instrument.broker) {
                scope.instrument.broker = -1;
                scope.brokerProfile = scope.brokerProfiles[0];
            }

            if(scope.instance){
                scope.instance.setDefaultValues = setDefaultValues;
            }

            var uniqueId = UniqueIdGenerator.generateId();
            var listenerId = "InstrumentDetails-" + uniqueId;

            SQEvents.addListener(listenerId, [
                SQEvents.get('EXCHANGES_CHANGED'),
                SQEvents.get('BROKERS_CHANGED'),                
                SQEvents.get('COUNTRIES_CHANGED'),
                SQEvents.get('SECTORS_CHANGED'),
                SQEvents.get('DATA_CHANGED')
            ], onEvent);

        }
    };
});