'use strict';

angular
  .module('angularJSApp.auth', [])
  .directive('autoFocus', function ($timeout) {
    return {
      link: function (scope, element, attrs) {
        attrs.$observe('autoFocus', function (newValue) {
          if (newValue === 'true')
            $timeout(function () {
              element[0].focus();
            });
        });
      },
    };
  })
  .controller('LoginCtrl', [
    '$scope',
    '$state',
    'ngToast',
    '$http',
    'Util',
    'configServer',
    '$cookies',
    'session',
    'Patterns',
    '$location',
    '$timeout',
    'AppUtil',
    'SessionType',
    'serviceKeyType',
    '$q',
    function (
      $scope,
      $state,
      ngToast,
      $http,
      Util,
      configServer,
      $cookies,
      session,
      Patterns,
      $location,
      $timeout,
      AppUtil,
      SessionType,
      serviceKeyType,
      $q
    ) {
      // check token in params URL
      var redirectPath = $location.search().redirectPath;
      var token = $location.search().tail;
      if (token) {
        //DECRYPT THE TOKEN
        token = window.atob(token);
        redirectPath = window.atob(redirectPath);
        session.setAccessToken(token, null);
        session.init(redirectPath);
      }

      // return deferred.promise;
      var defaultLanguage = session.getCurrentLanguage();
      session.changeLanguage(defaultLanguage);
      //list of team of a user
      $scope.user_team = {};
      $scope.keepLogin = false;

      $scope.formatDateTime = function (date) {
        return Util.formatDate(moment(date), $scope.currentUser.time_zone, 'MM/DD/YYYY HH:mm:ss');
      };

      var stopped;
      // The way to use alert
      $scope.alerts = [];
      $scope.closeAlert = function (index) {
        $scope.alerts.splice(index, 1);
        $scope.stop();
      };
      $scope.counter = 0;
      $scope.login_step1 = true;
      $scope.login_step2 = false;
      $scope.login_step3 = false;
      $scope.submitting = false;
      $scope.keepLogin = false;
      $scope.authenCode = '';
      $scope.loginInfo = {
        username: '',
        password: '',
      };

      $scope.email_pattern = Patterns.EMAIL_PATTERN;

      $scope.doLoginStep1 = function (valid) {
        if (!valid || $scope.loginInfo.username === '') {
          return;
        }
        $scope.submitting = true;
        var params = {
          //   email: AESEncrypter.encode($scope.loginInfo.username),
          email: $scope.loginInfo.username,
          service_key: serviceKeyType.SECURE_MAIL,
        };
        Util.createRequest(
          configServer.API_URL + '/auth/user/teams',
          'GET',
          params,
          function (response) {
            var status = response.status;
            if (status === 200) {
              $scope.user_team = response;
              if ($scope.user_team.data.length > 5) {
                $scope.listTeamCss = {
                  'max-height': '150px',
                  'overflow-y': 'scroll',
                  'margin-bottom': '10px',
                };
              }
              $scope.login_step1 = false;
              $scope.login_step2 = true;
              $scope.login_step3 = false;

              if ($scope.user_team && $scope.user_team.data && $scope.user_team.data.length === 1) {
                $scope.isSessionAge =
                  $scope.user_team.data && $scope.user_team.data[0].session_age !== 0;
              }

              if ($scope.user_team && $scope.user_team.data && $scope.user_team.data.length > 1) {
                $scope.$watch('user_team.team', function (newVal, oldVal) {
                  $scope.isSessionAge = newVal && newVal.session_age !== 0;
                  if (!angular.equals(oldVal, newVal)) {
                    $scope.stop();
                  }
                });
              }
            } else {
              if (status === 313) {
                Util.createToast({
                  className: 'danger',
                  content: 'ERROR.INVALID_LOGIN_CREDENTIAL',
                });
              } else {
                Util.createToast({ className: 'danger', content: 'SERVER_ERROR.' + status });
              }
            }
            $scope.submitting = false;
          },
          function (error) {
            Util.createToast({
              className: 'danger',
              content: 'SERVER_ERROR.' + error.status,
            });
            $scope.submitting = false;
          }
        );
      };

      $scope.doLoginStep2 = function (valid) {
        if (!valid) {
          return;
        }
        $scope.teamId = '';

        if ($scope.user_team.data.length === 1) {
          $scope.teamId = $scope.user_team.data[0].team_id;
        } else {
          $scope.teamId = $scope.user_team.team ? $scope.user_team.team.team_id : undefined;
        }

        if (typeof $scope.teamId === 'undefined') {
          $scope.alerts.push({
            type: 'danger',
            msg: Util.translateI18Next('LOGIN.ERROR_CHOOSE_TEAM'),
          });
          $scope.alerts = $scope.alerts.slice($scope.alerts.length - 1, $scope.alerts.length);
          $scope.submitting = false;
          return;
        }

        $scope.submitting = true;

        var loginParams = {
          team_id: $scope.teamId,
          //   email: AESEncrypter.encode($scope.loginInfo.username),
          email: $scope.loginInfo.username,
          password_hash: AESEncrypter.encode(Util.MD5($scope.loginInfo.password)),
          // password_hash: Util.MD5($scope.loginInfo.password),
          keep_login: $scope.keepLogin,
        };

        session.userLogin(
          loginParams,
          function (data, path) {
            $scope.alerts = [];
            if (path.indexOf('#') !== -1) {
              path = path.substring(path.indexOf('#') + 2);
            }
            if (data.data.type === SessionType.OTP_SESSION) {
              // 2-FA
              $scope.login_step1 = false;
              $scope.login_step2 = false;
              $scope.login_step3 = true;
              $scope.submitting = false;
              $scope.authenCode = '';
            } else if (data.data.type === SessionType.PASSWORD_POLICY_SESSION) {
              // password expire
              if (data.data.password_expire === true) {
                // password expired date
                session.getPasswordPolicySetting(data.data.session_id, function (data) {
                  $state.go('resetPass', {
                    token: data,
                    //   hash: AESEncrypter.encode($scope.loginInfo.username),
                    hash: $scope.loginInfo.username,
                    keep: $scope.keepLogin,
                    team: $scope.teamId,
                  });
                });
              } else {
                // check first time login
                $state.go('resetPass', {
                  token: session.getFirstTimeLoginToken(),
                  //   hash: AESEncrypter.encode($scope.loginInfo.username),
                  hash: $scope.loginInfo.username,
                  keep: $scope.keepLogin,
                  team: $scope.teamId,
                });
              }
            } else if (data.data.type === 0 && !data.data.session_id && data.data.account_lockout) {
              // account lockout

              $scope.counter = data.data.time_remain;

              $scope.countdown();
            } else {
              $location.path(path);
            }
            $scope.submitting = false;
          },
          function (error) {
            $scope.stop();
            if (error.status === 112) {
              $scope.alerts.push({
                type: 'danger',
                msg: Util.translateI18Next('SERVER_ERROR.112'),
              });
            } else {
              Util.createToast({ className: 'danger', content: 'SERVER_ERROR.' + error.status });

              /*  get the number of remaining attempts to enter the password
                                If null is returned, the team does not use the account lock function */
              if (error.status === 100) {
                Util.createRequest(
                  configServer.API_URL + '/auth/user/password/remain',
                  'GET',
                  {
                    // email: AESEncrypter.encode($scope.loginInfo.username),
                    email: $scope.loginInfo.username,
                    team_id: $scope.teamId,
                  },
                  function (data) {
                    if (data.data.number_remain) {
                      $scope.alerts.push({
                        type: 'warning',
                        msg: Util.translateI18Next('ERROR.PASSWORD_REMAIN', {
                          remain: data.data.number_remain,
                          threshold: data.data.threshold,
                        }),
                      });
                    }
                  }
                );
              }
            }
            $scope.submitting = false;
          }
        );
      };

      $scope.countdown = function () {
        $timeout.cancel(stopped);
        stopped = $timeout(function () {
          $scope.counter--;
          $scope.alerts = [];
          $scope.alerts.push({
            type: 'danger',
            msg: Util.translateI18Next('ERROR.ACCOUNT_LOCKOUT', {
              duration: AppUtil.convertSecondToTime($scope.counter),
            }),
          });

          if ($scope.counter === 0) {
            $scope.stop();
            $scope.submit = false;
          } else {
            $scope.countdown();
          }
        }, 1000);
      };

      $scope.stop = function () {
        $scope.alerts = [];
        $timeout.cancel(stopped);
      };

      $scope.doLoginStep3 = function (valid) {
        if (!valid) {
          return;
        }
        var params = {
          auth_code: $scope.authenCode,
          auth_token: session.getOTPToken(),
          keep_login: session.getKeepLogin(),
        };

        session.loginOTP(
          params,
          function (data, path) {
            if (path.indexOf('#') !== -1) {
              path = path.substring(path.indexOf('#') + 2);
            }
            if (data.data.type === SessionType.PASSWORD_POLICY_SESSION) {
              $state.go('resetPass', {
                token: data.data.session_id,
              });
            } else {
              $location.path(path);
            }

            $scope.submit = false;
          },
          function (error) {
            $scope.submitting = false;
          }
        );
      };

      $scope.backLoginStep1 = function () {
        //clean data
        $scope.login_step1 = true;
        $scope.login_step2 = false;
        $scope.login_step3 = false;
        $scope.submitting = false;
        $scope.stop();
        $scope.loginInfo.password = '';
      };
      $scope.backLoginStep2 = function () {
        //clean data
        $scope.login_step1 = false;
        $scope.login_step2 = true;
        $scope.login_step3 = false;
        $scope.submitting = false;
        $scope.loginInfo.password = '';
      };
    },
  ]);
