﻿(function () {
    'use-strict';

    app.controller('profileController', ['judgeRulesService', 'memberEditService', '$rootScope', '$scope', '$http', '$location', 'membershipCategories', 'stateProvinces',
        function (judgeRulesService, memberEditService, $rootScope, $scope, $http, $location, membershipCategories, stateProvinces) {

            $scope.serverErrors = [];
            $scope.categories = membershipCategories;
            $scope.isSubmitting = false;
            $scope.currentDate = new Date();
            $scope.stateProvinces = stateProvinces;

            $scope.countries = Object.keys($scope.stateProvinces);

            var DEFAULT_COUNTRY = 'United States';

            $scope.handlePayButton = function () {
                if (!$scope.user.hasFilledInProfile) {
                    memberEditService.confirmationPaymentModal().then(function (callback) {
                        if (callback) {
                            _onSubmit();
                        }
                    });
                } else {
                    _onSubmit();
                }
            };

            $scope.user = {
                country: DEFAULT_COUNTRY,
                stateProvince: null,
                birthdate: new Date(),
                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.onSubmit = _onSubmit;
            $scope.requiresCreditCardInformation = _requiresCreditCardInformation;
            $scope.canEditMembershipCategory = _canEditMembershipCategory;

            $scope.onCategoryChanged = _onCategoryChanged;

            function _getBlankCreditCard() {
                return {
                    type: 'MasterCard',
                    country: DEFAULT_COUNTRY,
                    stateProvince: null,
                    expirationMonth: null,
                    expirationYear: null
                };
            }

            $scope.getRange = _getRange;

            $scope.showValidations = _showValidations;

            _init();

            function _showValidations() {
                if ($scope.userprofileForm.$invalid) {
                    angular.forEach($scope.userprofileForm.$error.required, function (field) {
                        if (field.$invalid) field.$dirty = true;
                    });
                }
            }

            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 _requiresCreditCardInformation() {
                return !$scope.user.isPayingByCheck && $scope.user.hasFilledInProfile != null && !$scope.user.hasFilledInProfile;
            }

            function _onSubmit() {
                $scope.isSubmitting = true;
                $scope.serverErrors = [];

                if ($scope.user.isPayingByCheck || $scope.user.hasFilledInProfile || $scope.user.isCompanyMember) {
                    $scope.user.creditCard = null;
                }
                if (!$scope.user.address2) {
                    $scope.user.address2 = null;
                }
                if (!$scope.user.secondaryEmailAddress) {
                    $scope.user.secondaryEmailAddress = null;
                }

                $http.post('/api/account/updateprofile', $scope.user)
                    .then(function (response) {
                        if (!$scope.user.hasFilledInProfile) {
                            $scope.user.membershipPaymentInformation = response.data;
                        }

                        $scope.user.hasFilledInProfile = true;
                        // Don't make this information visable on the page anymore.
                        $scope.user.creditCard = _getBlankCreditCard();
                        toastr.success('Updated.');
                    })
                    .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 () {
                        if ($scope.user.isPayingByCheck) {
                            $scope.user.creditCard = _getBlankCreditCard();
                        }
                        $scope.isSubmitting = false;
                    });
            }


            function _canEditMembershipCategory() {
                var user = $scope.user;

                if (!user.isCompanyMember) {
                    return false;
                }

                if (user.hasFilledInProfile) {
                    return false;
                }

                if (user.judgeApprovalStatus) {
                    return false;
                }

                return true;
            }

            function _init() {
                // get existing profile information
                $http.get('/api/account/getprofile')
                    .then(function (result) {
                        var defaults = $scope.user;

                        $scope.user = result.data;
                        if (!result.data.hasFilledInProfile) {
                            $scope.user.country = $scope.user.country || defaults.country;
                            $scope.user.stateProvince = $scope.user.stateProvince || defaults.stateProvince;
                            $scope.user.birthdate = $scope.user.birthdate || defaults.birthdate;
                            $scope.user.creditCard = defaults.creditCard;


                            // Extend overwrites false values...
                            $scope.user.isPayingByCheck = result.data.isPayingByCheck;
                            $scope.user.isPhysicalMagazineCopy = result.data.isPhysicalMagazineCopy;
                            $scope.user.hasFilledInProfile = result.data.hasFilledInProfile;

                            if ($scope.user.membershipCategory.inputs.length === 0) {
                                var category = membershipCategories[$scope.user.membershipCategory.name];
                                if (category) {
                                    $scope.user.membershipCategory.inputs =
                                        $.map(category.inputs, function (input, index) {
                                            return { label: input.label, values: new Array(input.textboxes) };
                                        });
                                }
                            }
                        }

                        // We'll never store their credit card, so set it as default values.
                        $scope.user.creditCard = defaults.creditCard;
                        $scope.user.birthdate = new Date($scope.user.birthdate);
                    })
                    .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.');
                    });

            }
        }]);
})();