/**
 * Created by shadeeka on 11/28/15.
 */
angular.module('app.controllers')

  .controller('AppCtrl', function ($scope, $rootScope, $ionicPlatform, $ionicPopover,propertyCache, $ionicModal, $ionicLoading, $timeout, $state, $log, $cordovaNetwork,$lockScreen,
                                   ModalViews,sparkDataService, Util, auditProtocol,$http,$interval,initService) {
    // app name
    this.appname = "myApp";
    var _self = this;
    var checkInternetFulltime="";

    $scope.ping = function () {
      $log.debug("ping ... "+_self.countPing);
      _self.countPing++;
      $http.get("http://"+propertyCache.config.syncIp+"/ping").then(function (response) {
        $log.debug("ping success "+response);
        _self.isOnline  = true;
        _self.isOffline  = false;
        Util.setIpAddress();
        $rootScope.$broadcast("update-line");
        Util.setNetworkStatus('online');
        //$scope.syncButtonData();
        //////////////////audit//////////////////////
        // var $audit = auditProtocol.getEvent("networkOnline");
        // sparkDataService.sendDataToServer($audit);
        /////////////////////////////////////////////////
      }, function () {
        $log.error("ping error "+response);
        _self.isOnline  = false;
        _self.isOffline  = true;
        Util.setIpAddress();
        Util.setNetworkStatus('offline');

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

    $scope.syncButtonData = function (){
      try {
        sparkDataService.tabChangeSync();
      }catch (error){
        //ignore error
      }
    }

    $scope.checkInternet = function () {
      $scope.ping();
      var checkInternetVar = $interval(function () {
        $scope.ping();
        if ((_self.isOnline!=undefined &&  _self.isOnline) ||  _self.countPing > 60) {//check five minute time for internet
          $interval.cancel(checkInternetVar);
        }
      }, 5000);

       if(checkInternetFulltime!=""){
         $interval.cancel(checkInternetFulltime);
       }

      checkInternetFulltime = $interval(function () {
        $scope.ping();
      }, 1000 * 60 * 2);
    }


    $ionicPlatform.ready(function () {
      _self.countPing=0;
      Util.setIpAddress();
      Util.setMacAdress();
      $scope.checkInternet();
      //_self.isOffline = $cordovaNetwork.isOffline();
      //_self.isOnline = $cordovaNetwork.isOnline();

    });

    $scope.clearFabs = function () {
      var fabs = document.getElementsByClassName('button-flt');
      if (fabs.length && fabs.length > 1) {
        fabs[0].remove();
      }
    };
    $scope.clearAllFabs = function () {
      var fabs = document.getElementsByClassName('button-flt');
      if (fabs.length && fabs.length >= 1) {
        fabs[0].remove();
      }
    };

    _self.logout = function () {
      if (localStorage.getItem("current_date") == sparkDataService.getFormattedCurrentDate() ) {//set current_day when logout only is same day
        localStorage.setItem("current_date", sparkDataService.getFormattedDate());
      }
      ///////////////////audit//////////////////////
      var $audit = auditProtocol.getEvent("logout");
      sparkDataService.sendDataToServer($audit)
      //////////////////////////////////////////////
      $state.go("login");
    }

    _self.goTo = function (name) {
      if (ModalViews.getView(name))
        ModalViews.getView(name).show();
    }
    _self.exit = function (name) {
      if (ModalViews.getView(name))
        ModalViews.getView(name).hide();
    }

    passcodeSettings.onCorrect=function(){
      console.log('correct!');
      //////////////////audit//////////////////////
      var $audit = auditProtocol.getEvent("unlockApp");
      sparkDataService.sendDataToServer($audit)
      /////////////////////////////////////////////////
    };
    passcodeSettings.onWrong= function (attemptNumber) {
      console.log(attemptNumber + ' wrong passcode attempt(s)');
    }


    _self.lock = function(){
      //////////////////audit//////////////////////
      var $audit = auditProtocol.getEvent("lockApp");
      $audit.data.reference.code = passcodeSettings.code;
      sparkDataService.sendDataToServer($audit)
      /////////////////////////////////////////////////
      $lockScreen.show(passcodeSettings);
    }
    // listen for Online event
    $rootScope.$on('$cordovaNetwork:online', function (event, networkState) {
      var onlineState = networkState;
      $log.debug("Online", networkState);
      _self.isOffline = false;
      _self.isOnline = true;
      Util.setIpAddress();
      Util.setNetworkStatus("online");

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

    // listen for Offline event
    $rootScope.$on('$cordovaNetwork:offline', function (event, networkState) {
      var offlineState = networkState;
      $log.debug("Offline", networkState);
      _self.isOffline = true;
      _self.isOnline = false;
      Util.setIpAddress();
      Util.setNetworkStatus("offline");

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