'use strict';

var LoginCtrl = ['$scope', '$http', '$location', '$routeParams', '$cookieStore', function ($scope, $http, $location, $routeParams, $cookieStore) {
    $scope.showOTP = false;
    $scope.submit = function () {
        if ($scope.showOTP) {
            var data = {username: $scope.username, password: $scope.password, otp: $scope.otp, ClientName: $scope.name};
        } else {
            var data = {username: $scope.username, password: $scope.password};
        }


        $http.
            post('/api/login', data).
            success(function () {
                var came_from = $routeParams.came_from;
                if (typeof came_from === 'undefined' || came_from === "" || came_from === "/login" || came_from === "/logout") {
                    came_from = "/";
                }
                $location.path(came_from).search({});
            }).
            error(function (data, status, headers, config) {
                if (status === 403 && ['Unknown Client', 'OTP not supplied', 'OTP is wrong'].indexOf(data) !== -1) {
                    $scope.showOTP = true;
                    $scope.clientID = $cookieStore.get('ClientID');
                    $scope.$apply();
                }
                $scope.toasts.push({Type: 'Danger', Message: data});
            });
    };
    $('#username').focus();
}];

var LogoutCtrl = ['$scope', '$http', '$location', function ($scope, $http, $location) {
    $http.
        post('/logout').
        success(function () {
            $scope.toasts.push({Type: 'Success', Message: 'Logged out'});
            $location.path('/')
        }).
        error(function (errorMessage) {
            $scope.toasts.push({Type: 'Danger', Message: errorMessage});
        });
}];
