angular.module('gosFrontend').controller('moduleOptionsCtrl', ['$scope', '$http', '$timeout', function($scope, $http, $timeout) {
    $scope.pickedString = '';
    $scope.limit_code = 'free';
    $scope.list = {};
    $scope.list.storeLimits = window.storeLimits;
    $scope.limit = {
        index: 0
    };
    $scope.list.module = {
        core: [],
        product: [],
        sale: [],
        report: [],
        webstore: []
    };

    $scope.list.pick = {
        core: [],
        product: [],
        sale: [],
        report: [],
        webstore: []
    };

    $scope.list.position = {
        core: [],
        product: [],
        sale: [],
        report: [],
        webstore: []
    };

    var data = window.listModule;
    var len = data.length;
    for (var i = 0; i < len; i++) {
        if (data[i].required) {
            $scope.list.pick[data[i].package_code].push(data[i]);
        } else {
            $scope.list.module[data[i].package_code].push(data[i]);
        }
    }
    angular.forEach(['core', 'product', 'sale', 'report', 'webstore'], function(code) {
        $scope.list.position[code] = _.pluck($scope.list.module[code], '_id');
    });

    $scope.add = function(module) {
        var idx = _.indexOf($scope.list.pick[module.package_code], module);
        if (idx === -1) {
            $scope.list.pick[module.package_code].push(module);
            var idx2 = _.indexOf($scope.list.module[module.package_code], module);
            if (idx2 > -1)
                $scope.list.module[module.package_code].splice(idx2, 1);
        }
    }

    $scope.remove = function(module) {
        var idx = _.indexOf($scope.list.pick[module.package_code], module);
        if (idx > -1) {
            $scope.list.pick[module.package_code].splice(idx, 1);
            var idx2 = $scope.list.position[module.package_code].indexOf(module._id);
            if (idx2 > -1) {
                $scope.list.module[module.package_code].splice(idx2, 0, module);
            }
        }
    }

    function calcPrice() {
        $scope.totalPrice = 0;
        var res = [];
        for (var i in $scope.list.pick) {
            angular.forEach($scope.list.pick[i], function(item) {
                res.push(item);
            })
        }
        angular.forEach(res, function(i) {
            $scope.totalPrice += i.price;
        })
        $scope.totalPrice += $scope.list.storeLimits[$scope.limit.index].price;
        $scope.pickedString = JSON.stringify(res);
    }

    $scope.$watch('list.pick', function(newVal) {
        if (newVal) {
            calcPrice();
        }
    }, true);

    $scope.selectSl = function(index) {
        $scope.limit.index = index;
        $scope.limit_code = $scope.list.storeLimits[$scope.limit.index].code;
        calcPrice();
    }
}]);
