angular.module("app").directive("instrumentChooser", function ($rootScope, $timeout, $q, SQConstants, SQEvents, UniqueIdGenerator, AppService, BackendService, L) {
    return {
        restrict: 'E',
        replace: true,
        templateUrl: "../app/directives/instrumentChooser/instrumentChooser.html",
        scope: {
            instance: '=',
            helpText: '@',
            infoOnly: '=',
            commissionSettings: '=', //show/hide commission settings
            ngDisabled: '='
        },
        link: function (scope, element, attrs) {

            function loadInstruments() {
                loadToArray(scope.instruments, angular.copy(SQConstants.getConstants().instruments));
                instrumentsDeffered.resolve();
            }

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

                scope.brokers = brokerProfiles;
                console.log('got brokers',scope.brokers);
                instrumentsDeffered.resolve();
            }

            function onEvent(event, data) {
                if(event == SQEvents.get('DATA_CHANGED')) {
                    scope.data = angular.copy(SQConstants.getConstants().data);
                } 
                else if(event == SQEvents.get('INSTRUMENTS_CHANGED')) {
                    loadInstruments();
                } else if(event == SQEvents.get('BROKERS_CHANGED')) {
                    loadBrokers();
                } 
        
                try { scope.$digest(); } catch (err) {}
            }

            /**
             * Returns false if some data with existing records is using this instrument
             */
            function isInstrumentEditable(instrumentName) {
                for (var i = 0; i < scope.data.length; i++) {
                    var data = scope.data[i];
                    if (valueFilled(currentSymbol) && data.symbol == currentSymbol) {
                        if (data.rows != 0) {
                            return false;
                        }
                    } else if (data.instrument == instrumentName) {
                        return false;
                    }
                }
                return true;
            }

            function setDataType(dataType){
                scope.newInstrument.dataType = dataType;

                scope.selectedInstrument = angular.merge(scope.selectedInstrument, getItem(scope.instruments, 'dataType', dataType) || {});
                if(scope.selectedInstrument){
                    scope.selectedInstrument.disabled = !isInstrumentEditable(scope.selectedInstrument.instrument);
                }
            
                scope.selected.instrument = scope.selectedInstrument ? scope.selectedInstrument.instrument : '';
            }

            scope.onInstrumentChange = function (instrument) {
                var instrumentName = instrument || scope.selected.instrument;
                
                scope.selectedInstrument = angular.merge(scope.selectedInstrument, getItem(scope.instruments, 'instrument', instrumentName) || {});
                scope.selectedInstrument.disabled = !isInstrumentEditable(instrumentName);
                
                scope.selected.instrument = scope.selectedInstrument ? scope.selectedInstrument.instrument : '';
            }

            scope.onAddInstrument = function () {
                scope.currentAction = "Add";
                scope.newInstrument.instrument = '';
                scope.newInstrument.description = '';
                scope.newDetails.setDefaultValues();

                try { scope.$digest(); } catch(err){}
                showPopup('#' + scope.popupId);
            }

            function onEditInstrument(instrument){
                scope.currentAction = "Edit";
                scope.newInstrument = getItem(scope.instruments, 'instrument', instrument);
                try { scope.$digest(); } catch(err){}
                showPopup('#' + scope.popupId);
            }

            scope.onSaveInstrument = function(form){
                if(form){
                    scope.errors = validate(form);
                    if(scope.errors) {
                        return;
                    }
                }

                scope.newInstrument.description = scope.newInstrument.description || 'not set';
        
                switch(scope.currentAction){
                    case 'Add':
                        BackendService.sendRequest('/instruments/addInstrument', scope.newInstrument, function(result){
                            $rootScope.showSuccess(L.tsq("Instrument added"));
                            hidePopup('#' + scope.popupId);
            
                            instrumentsDeffered = $q.defer();
                            instrumentsDeffered.promise.then(function () {
                                scope.onInstrumentChange(scope.newInstrument.instrument);
                                scope.selected.instrument = scope.newInstrument.instrument;
                            });
                        });
                        break;
                    case 'Edit':
                        BackendService.getPromise('/instruments/editInstrument', scope.newInstrument).then(function(result){
                            if(result.data.success){
                                $rootScope.showSuccess(L.tsq("Instrument modified"));
                                hidePopup('#' + scope.popupId);
                            }
                            else {
                                if(result.data.error.length > 70){
                                    $rootScope.showErrorModal('Error', result.data.error, false, true);
                                }
                                else {
                                    $rootScope.showError(result.data.error);
                                }
                            }
                        });
                        break;
                }
            }

            scope.getBrokerProfileLabel = function(){
                if (!scope.broker) return L.tsq('All broker profiles');
        
                var brokerProfile = getItem(scope.brokers, 'id', scope.broker);
                return brokerProfile ? brokerProfile.name : '';
            }

            scope.onBrokerChange = function(){
                var brokerId = '';
                var broker = getItem(scope.brokers, 'id', scope.broker);
                if (broker){
                    brokerId = broker.id;
                }

                var instruments = angular.copy(SQConstants.getConstants().instruments);
                if (brokerId!=''){
                    instruments = instruments.filter(function(instrument){
                        return instrument.broker == brokerId;
                    }); 
                }
                loadToArray(scope.instruments, instruments);
                instrumentsDeffered.resolve();

                scope.selected.instrument = scope.instruments.length > 0 ? scope.instruments[0].instrument : '';
                scope.selectedInstrument = getItem(scope.instruments, 'instrument', scope.selected.instrument) || {};   
            }

            //- Event Handlers --------------------------------------------------------------

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

            //- Initialization --------------------------------------------------------------

            var uniqueId = UniqueIdGenerator.generateId();
            var listenerId = "InstrumentChooser-" + uniqueId;
            var instrumentsDeffered = $q.defer();
            var currentSymbol = null;

            scope.popupId = "Popup-" + uniqueId;
            scope.broker='';
            
            scope.instruments = [];
            scope.brokers = [];
            scope.data = angular.copy(SQConstants.getConstants().data);

            loadInstruments();
            loadBrokers();

            scope.selectedInstrument = {};
            scope.selected = { instrument : ''};
            scope.newInstrument = {};
            scope.newDetails = {};

            if(scope.instance){
                scope.instance.onEditInstrument = onEditInstrument;
                scope.instance.onAddInstrument = scope.onAddInstrument;
                scope.instance.setSymbol = function(symbol) { currentSymbol = symbol;}
                scope.instance.reset = function() { scope.broker=''; loadInstruments();}
                scope.instance.setDataType = setDataType;
                scope.instance.getInstrument = function(){ return scope.selectedInstrument; }
                scope.instance.selectInstrument = scope.onInstrumentChange;
            }

            SQEvents.addListener(listenerId, [
                SQEvents.get('INSTRUMENTS_CHANGED'),
                SQEvents.get('BROKERS_CHANGED'),
                SQEvents.get('DATA_CHANGED')
            ], onEvent);

        }
    };
});