/**
 * Created by shadeeka on 12/13/15.
 */
angular.module('app.controllers')

  .controller('HomeCtrl', function ($scope, $rootScope, $state, $filter, $cordovaFile, $cordovaFileTransfer, $ionicPlatform, ionicMaterialInk, $timeout, $log, $interval, $q, layoutConfig, eventProtocol,
                                    eventMediator, auditProtocol, dataPersistenceService, preConditions, sparkDataService, initService, undoOperation, cacheViews, propertyCache, LoadingMsg, $ionicPopup) {

    var _self = this;

    //button descriptor
    _self.layoutDef = layoutConfig.getLayout();

    _self.cache;

    _self.sync_in_progress = false;

    _self.isSynced = false;

    _self.buttonPress = false;

    _self.isUpdated = false;

    _self.loadingId = "";


    //initialization data
    //TODO: get data from database and update model here
    _self.init = function () {

      $log.debug("initializing model from cache");

      initService.loadInitialData().then(function (countData) {

          angular.forEach(_self.layoutDef.home, function (row, index) {
            angular.forEach(row.children, function (column, index) {
              var countObj = $filter('filter')(countData, {name: column.dataType});
              if (countObj.length) {
                column.value = countObj[0].count;
              }
            });
          });
          LoadingMsg.hideLoading(_self.loadingId);
        }, function (err) {
          angular.forEach(_self.layoutDef.home, function (row, index) {
            angular.forEach(row.children, function (column, index) {
              //var countObj = $filter('filter')(countData, {name: column.dataType});
              //if (countObj.length) {
              column.value = 0;
              //}
            });
          });
          //$log.debug("Error result :", countData);
          LoadingMsg.hideLoading(_self.loadingId);
        }
      );
      _self.cache = preConditions.getConfigData();
    };

    //do database calls after app gets ready and established connections to database
    $ionicPlatform.ready(function () {
      _self.init();
    });


    var failedImages = []
    var successImages = []
    var ImageLocation

    var factory = propertyCache.config.factory
    var module = propertyCache.config.line
    var tenant = propertyCache.config.tenant
    var options = {'directory': 'upload'};
    document.addEventListener('deviceready', function () {
      ImageLocation = cordova.file.dataDirectory + '/silhouetteList/';
    });

    _self.downloadImages = function () {
      var trustHosts = true
      angular.forEach(failedImages, function (silihoutteName, key) {
        var index = failedImages.indexOf(silihoutteName);
        failedImages.splice(index, 1);
        //var url = "http://nfs-integration.eastus.cloudapp.azure.com:9000/assets/ionic/img/silhouettes/" + silihoutteName + ".svg";
        var url = 'http://' + propertyCache.config.syncIp + '/dataman/getsiluhoutteimage?tenant=' + tenant + '&factory=' + factory + '&siluhoutteName=' + silihoutteName;
        var filename = url.split("=").pop();
        var targetPath = ImageLocation + filename;
        $cordovaFileTransfer.download(url, targetPath, options, trustHosts)
          .then(function (success) { // Success!
          }, function (error) { // Error

          }, function (progress) {

          });
      });
    }

    _self.checkImages = function () {
      var frontURI = ImageLocation + propertyCache.day_start.siluhoutteid + "_Front.svg"
      var backURI = ImageLocation + propertyCache.day_start.siluhoutteid + "_Back.svg"
      $cordovaFile.checkFile(ImageLocation, frontURI.split("/").pop())
        .then(function (success) {
          successImages.push(propertyCache.day_start.siluhoutteid + "_Front.svg")
        }, function (error) {
          failedImages.push(propertyCache.day_start.siluhoutteid + "_Front.svg")
          _self.downloadImages();
        });
      $cordovaFile.checkFile(ImageLocation, backURI.split("/").pop())
        .then(function (success) {
          successImages.push(propertyCache.day_start.siluhoutteid + "_Back.svg")
        }, function (error) {
          failedImages.push(propertyCache.day_start.siluhoutteid + "_Back.svg")
          _self.downloadImages();
        });
    };


    //handle button events
    _self.click = function (uiModel) {
      if (localStorage.getItem("current_date") != sparkDataService.getFormattedCurrentDate() && localStorage.getItem("current_date") != null) {

        /* preConditions.setCache(false);
         var  ds = new Object();
         ds.sessionPlan = "";
         ds.style = "";
         ds.members = "";
         ds.key1="";
         ds.key2 ="";
         ds.siluhoutteid= "";
         propertyCache.setDayStart(ds)*/
        preConditions.isAvailableDayStart();
        //_self.init();
      }
      localStorage.setItem("current_date", sparkDataService.getFormattedDate());
      this.reworkList = [];

      $log.debug("ng event :", uiModel.dataType);
      if (preConditions.isAvailableDayStart()) {
        if (uiModel.dataType == 'rwtogood') {

          if (propertyCache.factoryConfigs.rwtogoodRectificationSteps == "true") {
            $state.go("app.rework");
          } else if (propertyCache.factoryConfigs.rwtogoodRectificationSteps == "false") {
            if (propertyCache.factoryConfigs.bulk_capturing && propertyCache.factoryConfigs.size_wise_events.indexOf("rwtogood") !== -1) {
              _self.triggerSizeWiseEvent(uiModel.dataType);
            } else {
              var millisecondsToWait = 600;
              self.defectCount = 0;
              if (!_self.buttonPress) {
                _self.buttonPress = true;
                setTimeout(function () {
                  dataPersistenceService.selectAllTheDailyCount().then(function (res) {
                    var _self = this;
                    var countData = [];
                    for (var i = 0; i < res.rows.length; i++) {
                      if (res.rows.item(i).Type == "defects") {
                        self.defectCount = res.rows.item(i).Count;
                      }
                    }
                    if (self.defectCount > uiModel.value) {
                      var $event = eventProtocol.getEvent('rwtogood');

                      var selectedReworkCategories = [];

                      // var dataObj = new Object();
                      // dataObj.id = selectedList[i].id;
                      // dataObj.name = selectedList[i].name;
                      // selectedReworkCategories.push(selectedList[i].name);

                      dataPersistenceService.removeAllDefectCategories($event);

                      $event.data.categories = selectedReworkCategories;

                      //send event to database
                      dataPersistenceService.dailyCountPreProcess($event);

                      sparkDataService.sendDataToServer($event);

                      ///////////////////audit//////////////////////
                      // var $audit = auditProtocol.getEvent('rwtogood');
                      // $audit.data.reference.categories = selectedReworkCategories;
                      // sparkDataService.sendDataToServer($audit)
                      /////////////////////////////////////////////////
                      $rootScope.$broadcast("modelCountUpdate", {type: "rwtogood"});

                      var dataToUndoService = new Object();
                      dataToUndoService.dataType = 'rwtogood';
                      dataToUndoService.jsonSent = $event.data;
                      dataToUndoService.categories = selectedReworkCategories;
                      undoOperation.setLastEvent(dataToUndoService);

                    } else {
                      var alertPopup = $ionicPopup.alert({
                        title: $filter('translate')('Warning'),
                        template: '<div class="nf-center nf-valign-wrapper">' +
                        '<ion-spinner icon="ripple" class="nf-text-white"></ion-spinner>' +
                        '<span>{{"NoDefectsToRework" | translate}}</span></div>'
                      });
                    }
                  }, function (err) {

                  });
                  _self.buttonPress = false;
                }, millisecondsToWait);

              }
            }
          }

        } else if (uiModel.dataType == 'defects') {
          cacheViews.toOperations = 0;
          _self.checkImages();
          $state.go("app.defects");

        } else if (uiModel.dataType == 'reject') {
          cacheViews.toOperations = 0;

          if (propertyCache.factoryConfigs.bulk_capturing && propertyCache.factoryConfigs.size_wise_events.indexOf("reject") !== -1) {
            _self.triggerSizeWiseEvent(uiModel.dataType);
          } else {
            $state.go("app.reject");
          }

        } else {

          if (propertyCache.factoryConfigs.bulk_capturing && propertyCache.factoryConfigs.size_wise_events.indexOf("ftt") !== -1) {
              _self.triggerSizeWiseEvent(uiModel.dataType);
          } else {
            var millisecondsToWait = 500;
            if (!_self.buttonPress) {
              _self.buttonPress = true;
              setTimeout(function () {
                var $event = eventProtocol.getEvent(uiModel.dataType);
                $log.debug("Return event -> eventProtocol  :", $event);

                uiModel.value++;

                //send event to database
                $event.count = uiModel.value;
                dataPersistenceService.updateDailyCount($event);

                //send event to database
                dataPersistenceService.selectDailyCount($event).then(function (res) {
                  $event.count = uiModel.value;
                  dataPersistenceService.updateDailyCount($event);
                }, function (err) {
                  $event.count = uiModel.value;
                  dataPersistenceService.insertDailyCount($event);
                });

                //set undo operation
                var dataToUndoService = new Object();
                dataToUndoService.dataType = uiModel.dataType;
                dataToUndoService.jsonSent = $event.data;
                undoOperation.setLastEvent(dataToUndoService);

                //send data to remote server
                sparkDataService.sendDataToServer($event);

                ///////////////////audit//////////////////////
                // var $audit = auditProtocol.getEvent(uiModel.dataType);
                // sparkDataService.sendDataToServer($audit)
                //////////////////////////////////////////////
                _self.buttonPress = false;

              }, millisecondsToWait);
            }
          }
        }
      }
    }

    _self.triggerSizeWiseEvent = function (triggeredEventType) {
      propertyCache.setTriggeredEvent(triggeredEventType);
      $state.go("app.reject_sizewise");
    }

    //handle undo here
    _self.undo = function () {
      $log.debug("handle undo here");
      undoOperation.clear();
    }

    _self.getButtonConfig = function (type) {
      var btn;
      angular.forEach(_self.layoutDef.home, function (row, index) {
        angular.forEach(row.children, function (column, index) {
          if (column.dataType == type) {
            btn = column;
            return btn;

          }
        });
      });
      return btn;
    }

    //use theme for this
    $scope.$on('onRepeatLast', function (scope, element, attrs) {
      ionicMaterialInk.displayEffect();
    });


    _self.updateButtonsAfterSync = function () {
      initService.loadInitialData().then(function (countData) {
          angular.forEach(_self.layoutDef.home, function (row, index) {
            angular.forEach(row.children, function (column, index) {
              var countObj = $filter('filter')(countData, {name: column.dataType});
              if (countObj.length) {
                $scope.localButton = _self.getButtonConfig(countObj[0].name);
                if ($scope.localButton) {
                  $scope.localButton.value = countObj[0].count;
                  console.log("Local Button ", $scope.localButton);
                  console.log("Local Button Count ", $scope.localButton.value);
                }
              }
            });
          });

        }, function (countData) {
          $log.debug("Error result :", countData);
        }
      );
      _self.isSynced = false;
    }


    /*TODO: handle cross-controller model updates*/
    $rootScope.$on("modelCountUpdate",
      function handleDefectUpdateEvent($event, args) {
        if (args.type == 'sync') {
          _self.isSynced = true;
        } else {
          var localButton = _self.getButtonConfig(args.type);
          if (localButton) {
            if (args.value != undefined && args.value != null) {
              localButton.value += args.value;
            } else {
              localButton.value++;
            }
          }
        }
      }
    );

    $rootScope.$on("undo-event",
      function handleDefectUpdateEvent($event, args) {
        var localButton = _self.getButtonConfig(args.type);
        if (localButton)
          if (args.value != undefined && args.value != null) {
            localButton.value += args.value;
          } else {
            localButton.value--;
          }
      }
    );
    $scope.$on('$ionicView.beforeEnter', function () {
      $scope.$parent.clearFabs();
      if (localStorage.getItem("current_date") != sparkDataService.getFormattedCurrentDate()) {
        /*preConditions.setCache(false);
         var  ds = new Object();
         ds.sessionPlan = "";
         ds.style = "";
         ds.members = "";
         ds.key1="";
         ds.key2 ="";
         ds.siluhoutteid= "";
         propertyCache.setDayStart(ds);*/
        _self.loadingId = LoadingMsg.showLoading();
        preConditions.isAvailableDayStart();
        _self.init();
      }
    });


    $scope.$on('$ionicView.enter', function () {
      if (preConditions.checkPreValidations()) {
        preConditions.isAvailableDayStart();
      }
      if (_self.isSynced)
        _self.updateButtonsAfterSync();
    });

    $rootScope.$on("update-btn-counts", function () {
        if (!_self.isUpdated) {
          $timeout(function () {
            console.log('update-btn-counts');
            _self.updateButtonsAfterSync();
          }, 4000);//wait 4 seconds to complete all insert
          _self.isUpdated = true;
        }
      }
    );
  });
