"use strict";
appCore.controller("LoginCtrl", ["$scope", "$http", "$timeout", "vServices", "jwtHelper", "authManager", "$location", "$state", function ($scope, $http, $timeout, vServices, jwtHelper, authManager, $location, $state) {
    $scope.data = {email: "", password: "", captcha: null};
    $scope.isAuthenticated = (authManager.isAuthenticated());
    const init = function () {
        if (authManager.isAuthenticated()) {
            $location.path("/");
        }
    };
    $scope.login = function () {
        if (!$scope.data.email) alert("Please fill the Email.");
        else if (!$scope.data.password) alert("Please fill the Password.");
        else {
            grecaptcha.ready(function () {
                grecaptcha.execute($scope.$root.constant.googleCaptchaSiteKey, {action: "login"}).then(function (captcha) {
                    $scope.data.captcha = captcha;
                    vServices.callApi("auth/login", "POST", $scope.data, {}, true).then(function (res, err) {
                        if (res && res.status) {
                            localStorage.setItem("id_token", res.token);
                            $scope.$root.mainLeft = $scope.$root.isAuthenticated = true;
                            $scope.$root.updateMenu();
                            $(document).find('div.grecaptcha-badge').remove();
                            window.location.href = "/dashboard?token="+Math.random();
                        } else if (err) {
                            alert(err);
                        }
                    });
                });
            });
        }
    };

    init();
}]);
