﻿(function () {
    'use-strict';

    angular.module('judgeapp').controller
        (
        'companyPaymentController',
        [
            'judgeRulesService',
            '$rootScope',
            '$scope',
            '$http',
            '$location',
            'stateProvinces',
            '$routeParams',
            CompanyPaymentController
        ]);

    function CompanyPaymentController
        (
        judgeRulesService,
        $rootScope,
        $scope,
        $http,
        $location,
        stateProvinces,
        $routeParams
    ) {

        $scope.serverErrors = [];
        $scope.isSubmitting = false;
        $scope.stateProvinces = stateProvinces;
        $scope.companyId = $routeParams.companyId;        
        $scope.countries = Object.keys($scope.stateProvinces);

        var DEFAULT_COUNTRY = 'United States';
        $scope.currentDate = new Date();

        $scope.user = {                       
            acceptedBylaws: false,
            isPayingByCheck: false,
            creditCard: _getBlankCreditCard()
        };

        $scope.onCreditCardCountryChanged = _onCreditCardCountryChanged;
        $scope.onSubmit = _onSubmit;

        $scope.handlePayButton = function () {
            $.awards.confirm({
                title: "Submit Payment",
                message: 'Once you have submitted payment, your payment method cannot be changed. Do you still wish to submit payment?',
                largeSize: false,
                okFunction: function () {
                        _onSubmit();
                },
                okText: "OK"
            });
        };

        $scope.getRange = _getRange;
   
        $scope.showValidations = _showValidations;
        $scope.error = '';
        $scope.showForm = false;
        $scope.isPaymentComplete = false;
        $scope.hasError = false;
        function _init() {            
            $http.get('/api/companyPayment/'+$scope.companyId )
                .then(function (result) {
                    // Don't make this information visable on the page anymore.
                    $scope.user = result.data;
                    $scope.user.creditCard = _getBlankCreditCard();
                    $scope.showForm = true;
                }, function (error) {
                        $scope.error = error.data.message;
                        $scope.hasError = true;
                        $scope.showForm = false;
                });
        }

        _init();

        function _onCreditCardCountryChanged() {
            $scope.user.creditCard.stateProvince = $scope.stateProvinces[$scope.user.creditCard.country][0];
        }

        function _getRange(total) {
            return new Array(total);
        }

        function _getBlankCreditCard() {
            return {
                type: 'MasterCard',
                country: DEFAULT_COUNTRY,
                stateProvince: null,
                expirationMonth: null,
                expirationYear: null
            };
        }

        function _showValidations() {
            if ($scope.signupForm.$invalid) {
                angular.forEach($scope.signupForm.$error.required, function (field) {
                    if (field.$invalid) field.$dirty = true;
                });
            }
        }        

        function _onSubmit() {
            $scope.isSubmitting = true;
            $scope.serverErrors = [];
            $scope.user.billingFirstName = $scope.user.creditCard.firstName;
            $scope.user.billingLastName = $scope.user.creditCard.lastName;
            $scope.user.billingAddress = $scope.user.creditCard.address;

            if ($scope.user.isPayingByCheck) {
                $scope.user.creditCard = null;
            }

            $http.post('/api/companyPayment', $scope.user)
                .then(function () {
                    // Don't make this information visable on the page anymore.
                    $scope.user.creditCard = _getBlankCreditCard();
                    $scope.isPaymentComplete = true;  
                    $scope.showForm = !$scope.isPaymentComplete;
                })
                .catch(function (response) {
                    if (response.status === 400) {
                        var modelState = response.data.modelState;
                        if (!modelState) {
                            toastr.error('Error. Contact Support.');
                        }

                        var messages = [];
                        for (var key in modelState) {
                            messages = messages.concat(modelState[key]);
                        }

                        $scope.serverErrors = messages;

                        return;
                    }
                    toastr.error('Error. Contact Support.');
                }).finally(function () {
                    $scope.isSubmitting = false;
                    if ($scope.user.isPayingByCheck) {
                        $scope.user.creditCard = _getBlankCreditCard();
                    }
                });
        }
    }
})();