angular.module("app").directive("swapSettings", function ($rootScope, BackendService, SQEvents, SQConstants, UniqueIdGenerator, L) {
    return {
        restrict: 'E',
        replace: true,
        templateUrl: "../app/directives/swapSettings/swapSettings.html",
        scope: {
            sqModel: '='
        },
        link: function (scope, element, attrs) {

            function loadSettings(){
                scope.config.useSwap = false;
                scope.config.swapType = scope.swapTypes.money;
                scope.config.swapLong = 0;
                scope.config.swapShort = 0;
                scope.config.tripleSwapOn = scope.tripleSwapOptions.WEDNESDAY;
                scope.config.rolloutHour = "23:00";

                if(scope.sqModel){
                    let elSwap = xmlToObject(scope.sqModel).find("Swap")[0];
                    scope.config.useSwap = getAttrBooleanValue(elSwap, "use", false);
                    scope.config.swapType = getAttrStringValue(elSwap, "type", scope.swapTypes.money);
                    scope.config.swapLong = getAttrFloatValue(elSwap, "long", 0);
                    scope.config.swapShort = getAttrFloatValue(elSwap, "short", 0);
                    scope.config.tripleSwapOn = getAttrStringValue(elSwap, "tripleSwapOn", scope.tripleSwapOptions.wednesday);
                    scope.config.rolloutHour = getAttrStringValue(elSwap, "rolloutHour", "23:00");
                }
            }

            function saveSettings(){
                let elSwap = xmlToObject("<Swap/>").find("Swap")[0];
                elSwap.setAttribute("use", scope.config.useSwap ? "true" : "false");
                elSwap.setAttribute("type", scope.config.swapType);
                elSwap.setAttribute("long", "" + scope.config.swapLong);
                elSwap.setAttribute("short", "" + scope.config.swapShort);
                elSwap.setAttribute("tripleSwapOn", "" + scope.config.tripleSwapOn);
                elSwap.setAttribute("rolloutHour", "" + scope.config.rolloutHour);
                scope.sqModel = xmlToString(elSwap);
            }

            scope.swapTypes = SQConstants.getConstants().swapTypes;
            scope.tripleSwapOptions = SQConstants.getConstants().tripleSwapOptions;
            scope.config = {};

            loadSettings();
            
            var destroyModelWatch = scope.$watch("sqModel", function (newValue, oldValue) {
                loadSettings();
            });

            var destroyConfigWatch = scope.$watch("config", function (newValue, oldValue) {
                saveSettings();
            }, true);

            scope.$on("$destroy", function () {
                destroyModelWatch();
                destroyConfigWatch();
            });
        }
    };
});