/**
 * Created by shadeeka on 12/14/15.
 */
var Materialize = {};
angular.module('app.controllers')
  .controller('LoginCtrl', function ($scope, $state, ionicMaterialInk, ionicMaterialMotion, $log, dataPersistenceService, $timeout, sparkDataService, propertyCache, auditProtocol, $ionicLoading,initService,WifiService,$rootScope) {


    this.appname = $scope.$parent.appname;
    var _self = this;
    $scope.appVerion = configData.version;
    //----------- Load rework items before view enter ----//
    _self.credentials = {username: '', password: ''};
    _self.login = {has_error: false};
    _self.loginOperations = function () {
      propertyCache.setCurrentUser(_self.credentials.username);

      sparkDataService.getSessionPlans();

      sparkDataService.getSiluhoutteNames();

      //sparkDataService.getOperationsForStyles();
      sparkDataService.getIssuesList();
      sparkDataService.getRejectList();
       //sparkDataService.getOperationsForStyles();

      sparkDataService.syncAuthentication();


      ///////////////////audit//////////////////////
      var $audit = auditProtocol.getEvent("login");
      sparkDataService.sendDataToServer($audit);
      //////////////////////////////////////////////


      dataPersistenceService.enableApp();
      _self.credentials = {username: '', password: ''};
      initService.clearMidNightData();
      $state.go("app.home");
    };

    _self.doLogin = function (credincials) {
      $ionicLoading.show({
        template: '<div class="nf-center nf-valign-wrapper"><ion-spinner icon="ripple" class="nf-text-white"></ion-spinner><span>Authenticating...</span></div>'
      });

      WifiService.setWifiEnabled(false);
      if (localStorage.getItem("current_date") != sparkDataService.getFormattedCurrentDate() && localStorage.getItem("current_date") != null) {
        $log.debug("********************** *********************************************************************");
        $log.debug("********************** Calling Yesterday data clearing Called once *************************");
        $log.debug("********************** localStorage Date"+localStorage.getItem("current_date") +"***********");
        $log.debug("********************** system  Date     "+sparkDataService.getFormattedCurrentDate() +"*****");
        $log.debug("********************** *********************************************************************");
        initService.logOutMidNightStartUp();
      }
      $timeout(function () {
        WifiService.setWifiEnabled(true);
        initService.loadingConfigData();
      }, 4000);

      $timeout(function () {//wait login for restart WIFI
        $rootScope.$broadcast("update-line");
      var bcrypt = dcodeIO.bcrypt;
      _self.login.has_error = false;
      dataPersistenceService.getAuthentication(_self.credentials.username).then(function (hashedPass) {

        if (bcrypt.compareSync(_self.credentials.password, hashedPass.rows.item(0).Password)) {
          _self.loginOperations();
          $ionicLoading.hide();

        } else {
          _self.login.has_error = true;
          $ionicLoading.hide();
          $log.debug("error occurred while login");
        }
      }).catch(function () {
        if (_self.credentials.username == "user" && _self.credentials.password == "user") {
          $ionicLoading.hide();
          _self.loginOperations()

        }
        else {
          _self.login.has_error = true;
          $ionicLoading.hide();
          $log.debug("error occurred while login");
        }
      });
      }, 15000);
    };

    /*TODO: put after login functions here*/
    _self.executeAfterLoginFunctions = function () {

      sparkDataService.syncAuthentication();
    }

    $scope.$on('$ionicView.beforeEnter', function () {
      console.log("before enter")

    });

  });
