﻿(function () {
    'use-strict';

    angular.module('judgeapp').controller
        (
        'SignupController',
        [
            'judgeRulesService',
            '$rootScope',
            '$scope',
            '$http',
            '$location',
            'stateProvinces',
            'membershipCategories',
            'memberEditService',
            SignupController
        ]);

    function SignupController
        (
        judgeRulesService,
        $rootScope,
        $scope,
        $http,
        $location,
        stateProvinces,
            membershipCategories,
            memberEditService
    ) {

        $scope.serverErrors = [];
        $scope.categories = membershipCategories;
        $scope.isSubmitting = false;

        $scope.stateProvinces = stateProvinces;

        $scope.countries = Object.keys($scope.stateProvinces);

        var DEFAULT_COUNTRY = 'United States';

        $scope.user = {
            country: DEFAULT_COUNTRY,
            stateProvince: null,
            birthdate: null,
            acceptedBylaws: false,
            isPayingByCheck: false,
            isPhysicalMagazineCopy: false,
            membershipCategory: {
                name: Object.keys($scope.categories)[0],
                inputs: [
                    //{
                    //    label: '',
                    //    values: ['']
                    //}
                ]
            },
            creditCard: _getBlankCreditCard(),
            memberReference1: {},
            memberReference2: {}
        };

        $scope.onCountryChanged = _onCountryChanged;
        $scope.onCreditCardCountryChanged = _onCreditCardCountryChanged;
        $scope.onCategoryChanged = _onCategoryChanged;
        $scope.onSubmit = _onSubmit;
        $scope.currentDate = new Date();
        $scope.getRange = _getRange;

        $scope.showValidations = _showValidations;

        _init();

        $scope.handlePayButton = function () {
            memberEditService.confirmationPaymentModal().then(function (callback) {
                if (callback) {
                    _onSubmit();
                }
            });
        };

        function _onCountryChanged() {
            $scope.user.stateProvince = $scope.stateProvinces[$scope.user.country][0];
        }

        function _onCreditCardCountryChanged() {
            $scope.user.creditCard.stateProvince = $scope.stateProvinces[$scope.user.creditCard.country][0];
        }

        function _onCategoryChanged() {
            $scope.user.membershipCategory.inputs = [];

            var category = $scope.categories[$scope.user.membershipCategory.name];

            angular.forEach(category.inputs, function (input, inputIndex) {
                $scope.user.membershipCategory.inputs[inputIndex] = { label: input.label, values: new Array(input.textboxes) }
            });
        }

        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;
                });
            }

            if ($scope.user.membershipCategory.name.trim() === "CHOOSE ONE") {
                $scope.signupForm.membershipCategoryName.$dirty = true;
                $scope.signupForm.membershipCategoryName.$error.required = true;
                $scope.signupForm.$invalid = true;

            } else {
                $scope.signupForm.membershipCategoryName.$dirty = false;
                $scope.signupForm.membershipCategoryName.$error.required = false;

            }
        }
        

        function _onSubmit() {
            $scope.isSubmitting = true;
            $scope.serverErrors = [];

            if ($scope.user.isPayingByCheck) {
                $scope.user.creditCard = null;
            }
            if (!$scope.user.address2) {
                $scope.user.address2 = null;
            }
            if (!$scope.user.secondaryEmailAddress) {
                $scope.user.secondaryEmailAddress = null;
            }

            $http.post('/api/account/signup', $scope.user)
                .then(function () {
                    // Don't make this information visable on the page anymore.
                    $scope.user.creditCard = _getBlankCreditCard();

                    $location.path('/signupCompleted');
                })
                .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();
                    }
                });
        }

        function _init() {
            _onCategoryChanged();
        }
    }
})();