'use strict';
app.controller('signInController', ['$scope', '$http', '$location', '$translate', 'lib', 'authService', 'blockUI', function ($scope, $http, $location, $translate, lib, authService, blockUI) {

	$scope.isOnPremises = lib.isOnPremises();
	$scope.loginUsername = '';
	$scope.loginPassword = '';

	var init = function () {
		if (authService.isAuthenticated()) {
			$location.path('/dashboard');
		}
	};

	$scope.loginWithGoogle = function () {
		blockUI.start();
		var redirectUri = document.location.href;
		redirectUri = redirectUri.substring(0, redirectUri.indexOf('#'));
		location.href = '/Api/Account/ExternalLogin?provider=Google&response_type=token&client_id=self&redirect_uri=' + encodeURIComponent(redirectUri);
	};

	$scope.login = function () {

		if ($scope.loginUsername === null || $scope.loginUsername === '') {
			$translate(['message', 'siFillUsername']).then(function (msgs) {
				lib.showAlert(msgs.message, msgs.siFillUsername);
			});
			return;
		}
		if ($scope.loginPassword === null || $scope.loginPassword === '') {
			$translate(['message', 'siFillPassword']).then(function (msgs) {
				lib.showAlert(msgs.message, msgs.siFillPassword);
			});
			return;
		}

		$http({
			method: 'POST',
			url: '/Token',
			data: $.param({
				grant_type: 'password',
				username: $scope.loginUsername,
				password: $scope.loginPassword
			}),
			headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
		}).then(function (response) {
			var token = response.data.access_token;
			$http.get('/Api/Account/UserInfo', {
				headers: { 'Authorization': 'Bearer ' + token }
			}).then(function (response) {
				authService.setAuthenticated(token, response.data);
			}, lib.handleIdentityError);
		}, lib.handleIdentityError);
	};

	init();

}]);
