'use strict';

angular
    .module('user-change-email', [])
    .controller('ChangeEmailCtrl', [
        '$scope', 'session', 'AppUtil', 'APIName', '$state', 'APIStatus', 'app', 'util', '$stateParams', 'logo',
        function ($scope, session, AppUtil, APIName, $state, APIStatus, app, util, $stateParams, logo) {
            $scope.logo = logo;
            $scope.currentUser = session.getUser();
            $scope.doBack = function () {
                if ($scope.currentUser === undefined) {
                    $state.go("adminLogin");
                } else {
                    $state.go(AppUtil.getLocation($scope.currentUser));
                }
            };
            $scope.pattern = app.EMAIL_PATTERN;
            // Do submit
            $scope.submit = false;
            $scope.userChangeEmail = function (valid) {

                if (!valid)
                    return;
                $scope.submit = true;
                // Prevent submit when no change
                var params = {
                    mail_address: $scope.mail_address,
                    confirm_code: $stateParams.confirm_code
                };
                // call Create Project ajax
                AppUtil.createRequest(APIName.UPDATE_EMAIL, params, function (data) {

                    $scope.submit = false;
                    var user = data.data;
                    // check user change own email
                    if ($scope.currentUser === undefined || $scope.currentUser === null) {
                        AppUtil.createToast({
                            text: util.translate(APIName.UPDATE_EMAIL.success_msg),
                            type: 'success'
                        });
                        $state.go("adminLogin");

                    } else {
                        $state.go(AppUtil.getLocation($scope.currentUser));
                        AppUtil.createToast({
                            text: util.translate(APIName.UPDATE_EMAIL.success_msg),
                            type: 'success'
                        });
                    }

                }, function (error) {
                    AppUtil.showError({
                        text: util.translate("sever_errors." + error.status)
                    });
                    $scope.submit = false;
                });
            };
        }]
    );
