'use strict';

/**
 * @ngdoc function
 * @name domainManagerApp.controller:MainCtrl
 * @description
 * # MainCtrl
 * Controller of the domainManagerApp
 */
 angular.module('domainManagerApp.signin', ['firebase', 'domainManagerApp.userData', 'angular-ladda'])
 .controller('SignInController', ['$scope', 'UserData', '$location', '$firebaseAuth', '$timeout', function ($scope, UserData, $location, $firebaseAuth, $timeout) {

    $scope.loading = false;
    var firebaseObj = new Firebase("https://j1x-cpanel.firebaseio.com");
    $scope.authObj = $firebaseAuth(firebaseObj);


    $scope.SignIn = function(event) {
      $scope.loading = true;
      event.preventDefault();  // To prevent form refresh
      var username = $scope.user.email;
      var password = $scope.user.password;

      $scope.authObj.$authWithPassword({
        email: username,
        password: password
      }).then(function(authData) {
        console.log("Logged in as:", authData.uid);
        $timeout(function() {
          $scope.loading = false; // stop loading
          UserData.set($scope.user.email, true);
          $location.path('/main');
        }, 1000);
      }).catch(function(error) {
        console.error("Authentication failed:", error);
        $timeout(function() {
          $scope.loading = false; // stop loading
        }, 1000);
      });
    }

    $scope.EmailCheck = function() {
      if($scope.signinForm.email.$invalid && $scope.signinForm.email.$dirty) {
        return true;
      } else {
        return false;
      }
    }

    $scope.PasswordCheck = function() {
      if($scope.signinForm.password.$error.minlength && $scope.signinForm.password.$dirty) {
        return true;
      } else {
        return false;
      }
    }

  }]);