angular.module('paymentModule')

    .directive('creditCardType', function () {
        return {
            require: 'ngModel',
            link: function (scope, elm, attrs, ctrl) {
                ctrl.$parsers.unshift(function (value) {
                    scope.ccinfo.type =
                        (/^5[1-5]/.test(value)) ? "mastercard"
                            : (/^4/.test(value)) ? "visa"
                                : (/^3[47]/.test(value)) ? 'amex'
                                    : (/^6011|65|64[4-9]|622(1(2[6-9]|[3-9]\d)|[2-8]\d{2}|9([01]\d|2[0-5]))/.test(value)) ? 'discover'
                                        : undefined
                    ctrl.$setValidity('invalid', !!scope.ccinfo.type)
                    return value
                })
            }
        }
    })

    .directive('cardExpiration', function () {
        return {
            require: 'ngModel',
            link: function (scope, elm, attrs, ctrl) {
                scope.$watch('[ccinfo.month,ccinfo.year]', function (value) {
                    ctrl.$setValidity('invalid', true);
                    if (+scope.ccinfo.month + 12 * scope.ccinfo.year < +scope.currentMonth + 12 * scope.currentYear) {
                        ctrl.$setValidity('invalid', false);
                    }
                    return value;
                }, true)
            }
        }
    })

    .filter('range', function () {
        return function (arr, lower, upper) {
            for (var i = lower; i <= upper; i++) {
                arr.push(i);
            }
            return arr;
        };
    })

    .filter('trustAsResourceUrl', ['$sce', function ($sce) {
        return function (val) {
            return $sce.trustAsResourceUrl(val);
        }
    }])

    .controller('paymentAddController', ['$scope', '$locale', 'paymentService', '$uibModal', function ($scope, $locale, paymentService, $uibModal) {

        $scope.stepwizard = 1;
        $scope.isBusy = false;
        $scope.isDatacomOpenining = false;
        var cardTokens = [];

        $scope.currentYear = new Date().getFullYear();
        $scope.currentMonth = new Date().getMonth() + 1;
        $scope.months = $locale.DATETIME_FORMATS.MONTH;
        $scope.ccinfo = { type: undefined };
        $scope.prefObj = { payment_type: undefined };
        $scope.cardTokens = function () { return cardTokens; };
        $scope.hasCardTokens = function () { return Boolean(cardTokens && cardTokens.length); };

        $scope.ngOnInit = function () {

            // load tokens
            $scope.loadTokens();
        };

        // open datacom popup for card processing
        $scope.openDatacom = function () {

            if ($scope.isDatacomOpenining) {
                return;
            }
            $scope.isDatacomOpenining = true;
            
            // generate OTP for customer card saving
            paymentService.tokenise_card().then(function (arr) {
                
                $scope.isDatacomOpenining = false;

                var parentScope = $scope;
                var modalInstance = $uibModal.open({
                    ariaLabelledBy: 'modal-title',
                    ariaDescribedBy: 'modal-body',
                    templateUrl: 'datacomModal',
                    controller: function ($scope, $uibModalInstance) {
                        $scope.datacom = arr;

                        $scope.closeDatacom = function () {

                            // close modal
                            $uibModalInstance.dismiss('cancel');
                            parentScope.loadTokens();
                        };
                    },
                    size: 'md'
                });

            });

        };

        // load tokens to the page
        $scope.loadTokens = function () {
            // load tokens for the customer.
            paymentService.getTokens().then(function (arr) {

                $scope.$evalAsync(function () {
                    cardTokens = arr; 
                });
            });
        };

        $scope.save = function (form, data) {
            if (!form.$valid) {
                return;
            }

            console.log(data); // valid data saving stuff here
            $scope.goToStep3();
        };

        $scope.savePreferences = function (form, data) {
            if (!form.$valid) {
                return;
            }
            $scope.goToStep3();
        };

        // confirm page which adds a new recurring payment via api
        $scope.confirm = function () {
            var newItem = { id: Date.now(), payment: $scope.prefObj };

            $scope.isBusy = true;

            // post to save to API
            paymentService.addCard(newItem).then(function (response) {

                $scope.prefObj['id'] = response; /// this is the new id within payment_recorrences
                $scope.goToStep4();
            });
        };

        $scope.onItemClick = function (id) {
            $scope.prefObj['payment_token_id'] = id;
        }
        $scope.getIsSelected = function (id) {
            return ($scope.prefObj['payment_token_id'] === id);
        };

        // updates an existing recurring record with the selected card token
        $scope.finalise = function () {

            // need a selected card before we can proceed
            if (typeof $scope.prefObj['payment_token_id'] == 'undefined') {
                alert('Please select a card');
                return false;
            }

            // update status
            $scope.prefObj['status'] = 'A';

            // post to save to API
            paymentService.editCard($scope.prefObj).then(function (response) {

                $scope.goToPaymentHome();
            });
        };

        $scope.goToStep1 = function () {
            $scope.stepwizard = 1;
            $scope.isBusy = false;
        };

        $scope.goToStep2 = function () {
            $scope.stepwizard = 2;
            $scope.isBusy = false;
        };

        $scope.goToStep3 = function () {
            $scope.stepwizard = 3;
            $scope.isBusy = false;
        };

        $scope.goToStep4 = function () {
            $scope.stepwizard = 4;
            $scope.isBusy = false;
        };

        $scope.goToPaymentHome = function () {
            window.location.href = '/payment_recurrences';
        };

        $scope.popover = null;
        $scope.togglePopover = function (popover) {
            if ($scope.popover === popover) {
                $scope.popover = null;
            } else {
                $scope.popover = popover;
            }
        };

    }]);