'use strict';
angular.module('changeEmail', [])
    .controller('ChangeEmail', ['$scope', '$state', 'ngToast', '$timeout', 'configServer', '$stateParams', 'Util', 'Patterns',
        function ($scope, $state, ngToast, $timeout, configServer, $stateParams, Util, Patterns) {
            $scope.doBack = function () {
                $state.go("login");
            };

            $scope.email_pattern = Patterns.EMAIL_PATTERN;
            // Do submit
            $scope.submit = false;
            $scope.changeEmailUser = function (valid) {
                if (!valid)
                    return;

                // Prevent submit when no change
                $scope.submit = true;
                var params = {
                    "mail_address": $scope.mail_address,
                    "confirm_code": $stateParams.confirm_code
                };
                Util.createRequest(configServer.API_URL + "/auth/user/email", "PUT", params, function (response) {
                    if (response.status === 200) {
                        Util.createToast({
                            className: 'success',
                            content: 'COMMON.MESSAGE.SAVE_SUCCESS'
                        });
                        $state.go("login");
                    } else {
                        Util.createToast({
                            className: 'danger',
                            content: 'SERVER_ERROR.' + response.status
                        });
                        if (response.status === 102) {
                            $state.go("login");
                        }
                        $scope.submit = false;
                    }
                }, function (error) {
                    Util.createToast({
                        className: 'danger',
                        content: 'SERVER_ERROR.' + error.status
                    });
                    if (error.status === 102) {
                        $state.go("login");
                    }
                    $scope.submit = false;
                });
            };

        }
    ]);
