/**
 * 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 = "";



    _self.loadStyleInfo = function () {
      _self.displayStyle = propertyCache.day_start.style;
      _self.displayKey1 = propertyCache.day_start.key1;
      _self.displayKey2 = propertyCache.day_start.key2;
      _self.displayMember = propertyCache.day_start.members;
    }

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

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

      _self.loadStyleInfo();

      _self.cache = preConditions.getConfigData();

      _self.startedStyles = propertyCache.startedStyles.styleNames;

      // _self.pos = propertyCache.startedPos.poNames;
      //
      // _self.colours = propertyCache.startedColors.colorCodes;

      this.selectCounts();

    };

    _self.populatePopus = function () {
      if(propertyCache.factoryConfigs.show_style_info_bar == "true") {

        // Initialing SOs
        dataPersistenceService.selectStartedSos(_self.displayStyle).then(function (result) {
          console.log("RESULTTTTTTTTTTTTTT -----> ", result);
          // self.styles = [];
          self.pos = [];
          self.colours = [];
          for (var i = 0; i < result.rows.length; i++) {
            // if ($.inArray(result.rows.item(i).Style, self.styles) == -1) {
            //   self.styles.push(result.rows.item(i).Style);
            // }
            if ($.inArray(result.rows.item(i).SO, self.pos) == -1) {
              self.pos.push(result.rows.item(i).SO);
            }
            if (result.rows.item(i).SO == _self.displayKey2) {
              if ($.inArray(result.rows.item(i).LI, self.colours) == -1) {
                self.colours.push(result.rows.item(i).LI);
              }
            }
          }
          // _self.styles = self.styles;
          _self.pos = self.pos;
          _self.colours = self.colours;
        });
      }
    }

    _self.selectCounts = function(){

      if(propertyCache.factoryConfigs.show_style_info_bar == "true"){

        _self.populatePopus();

        initService.loadInitialData(true).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;
                }else {
                  column.value = 0;
                }
              });
            });
            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);
          }
        );

      }else{

        initService.loadInitialData(false).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);
          }
        );

      }

    }

    //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) {

      _self.loadStyleInfo();

      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
                if(propertyCache.factoryConfigs.show_style_info_bar == "true") {
                  dataPersistenceService.selectStyleSoLiWiseDailyCount($event).then(function (res) {
                    $event.count = uiModel.value;
                    dataPersistenceService.updateDailyCount($event);
                  }, function (err) {
                    $event.count = uiModel.value;
                    dataPersistenceService.insertDailyCount($event);
                  });
                }else{
                  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--;
          }
      }
    );

    $rootScope.$on("reload-button-count",
      function reloadButtonCounts() {
        _self.selectCounts();
      }
    );

    $scope.$on('$ionicView.beforeEnter', function () {
      $scope.$parent.clearFabs();
      preConditions.isAvailableDayStart();
      _self.populatePopus();
      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(propertyCache.factoryConfigs.show_style_info_bar == "true"){
        _self.showStyleBar=true;
        _self.styleTop="top:30px!important;";
        _self.styleBottom="height-92";
        _self.homeStyle = "home-button-style-stylewise";
      }else{
        _self.showStyleBar=false;
        _self.styleTop="";
        _self.styleBottom="height-100";
        _self.homeStyle = "home-button-style";
      }


      //$timeout(function () {
       // _self.loadStyleInfo();
    //  },1000);

      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;
        }
      }
    );


    $rootScope.$on("update-style-info", function () {
        _self.loadStyleInfo();
      }
    );

    $rootScope.$on("update-daystart", function () {
      _self.populatePopus();
      }
    );


    ////////////// popups ////////////////////

    _self.showStylePopup = function () {
      _self.styleBefore = _self.displayStyle;
      $scope.selectedStyle = {};
      // An elaborate, custom popup
      var planPopup = $ionicPopup.show({
        template: '<ion-list><ion-radio ng-repeat="style in homectrl.startedStyles" ng-model="homectrl.displayStyle" ng-value=" \'{{style}}\' "> ' +
        '<div class="item item-text-wrap">{{style}}</div> </ion-radio> </ion-list>',
        title: 'Select a Style',
        cssClass: "custom-popup",
        scope: $scope,
        buttons: [
          {text: 'Cancel'},
          {
            text: '<b>Done</b>',
            type: 'button-positive',
            onTap: function (e) {
              if (!_self.displayStyle) {
                //don't allow the user to close unless he enters wifi password
                e.preventDefault();
              } else {
                _self.displayKey1 = "";
                _self.displayKey2 = "";
                dataPersistenceService.selectStartedSos(_self.displayStyle).then(function (result) {
                  console.log("RESULTTTTTTTTTTTTTT -----> ", result);
                  self.pos = [];
                  self.colours = [];
                  for (var i = 0; i < result.rows.length; i++) {
                    if ($.inArray(result.rows.item(i).SO, self.pos) == -1) {
                      self.pos.push(result.rows.item(i).SO);
                    }
                    if ($.inArray(result.rows.item(i).LI, self.colours) == -1) {
                      self.colours.push(result.rows.item(i).LI);
                    }
                  }
                  _self.pos = self.pos;
                  _self.colours = self.colours;


                });
                propertyCache.day_start.style = _self.displayStyle;
                _self.selectCounts();
                return _self.displayStyle;
              }
            }
          }
        ]
      });

      planPopup.then(function (res) {
        if (res) {
          _self.displayStyle = res;
        } else {
          _self.displayStyle = _self.styleBefore;
        }
      });
    };

    _self.showPoPopup = function () {
      _self.soBefore = _self.displayKey2;
      $scope.selectedPo = {};
      // An elaborate, custom popup
      var planPopup = $ionicPopup.show({
        template: '<ion-list><ion-radio ng-repeat="key2 in homectrl.pos" ng-model="homectrl.displayKey2" ng-value=" \'{{key2}}\' "> ' +
        '<div class="item item-text-wrap">{{key2}}</div> </ion-radio> </ion-list>',
        title: 'Select a PO no',
        cssClass: "custom-popup",
        scope: $scope,
        buttons: [
          {text: 'Cancel'},
          {
            text: '<b>Done</b>',
            type: 'button-positive',
            onTap: function (e) {
              if (!_self.displayKey2) {
                //don't allow the user to close unless he enters wifi password
                e.preventDefault();
              } else {
                _self.displayKey1 = "";
                //_self.cached_params.key2 = "";
                dataPersistenceService.selectStartedLis(_self.displayStyle,_self.displayKey2).then(function (result) {
                  console.log("RESULTTTTTTTTTTTTTT -----> ", result);
                  self.styles = [];
                  self.colours = [];
                  for (var i = 0; i < result.rows.length; i++) {
                    if(result.rows.item(i).Style == _self.displayStyle){
                      if ($.inArray(result.rows.item(i).LI, self.colours) == -1) {
                        self.colours.push(result.rows.item(i).LI);
                      }
                    }
                    if ($.inArray(result.rows.item(i).Style, self.styles) == -1) {
                      self.styles.push(result.rows.item(i).Style);
                    }
                  }
                  _self.styles = self.styles;
                  _self.colours = self.colours;


                });
                propertyCache.day_start.key2 = _self.displayKey2;
                _self.selectCounts();
                return _self.displayKey2;
              }
            }
          }
        ]
      });

      planPopup.then(function (res) {
        if (res) {
          _self.displayKey2 = res;
        } else {
          _self.displayKey2 = _self.soBefore;
        }
      });
    };


    _self.showColourPopup = function () {
      _self.liBefore = _self.displayKey1;
      $scope.selectedColour = {};
      // An elaborate, custom popup
      var planPopup = $ionicPopup.show({
        template: '<ion-list><ion-radio ng-repeat="key1 in homectrl.colours" ng-model="homectrl.displayKey1" ng-value=" \'{{key1}}\' "> ' +
        '<div class="item item-text-wrap">{{key1}}</div> </ion-radio> </ion-list>',
        title: _self.title,
        cssClass: "custom-popup",
        scope: $scope,
        buttons: [
          {text: 'Cancel'},
          {
            text: '<b>Done</b>',
            type: 'button-positive',
            onTap: function (e) {
              if (!_self.displayKey1) {
                //don't allow the user to close unless he enters wifi password
                e.preventDefault();
              } else {
                /*dataPersistenceService.selectStylesPos(_self.displayKey1).then(function (result) {
                  console.log("RESULTTTTTTTTTTTTTT -----> ", result);
                  self.styles = [];
                  self.pos = [];
                  for (var i = 0; i < result.rows.length; i++) {
                    if ($.inArray(result.rows.item(i).Po, self.pos) == -1) {
                      self.pos.push(result.rows.item(i).Po);
                    }
                    if ($.inArray(result.rows.item(i).Style, self.styles) == -1) {
                      self.styles.push(result.rows.item(i).Style);
                    }
                  }
                  _self.styles = self.styles;
                  _self.pos = self.pos;


                });*/
                propertyCache.day_start.key1 = _self.displayKey1;
                _self.selectCounts();
                return _self.displayKey1;
              }
            }
          }
        ]
      });

      planPopup.then(function (res) {
        if (res) {
          _self.displayKey1 = res;
        } else {
          _self.displayKey1 = _self.liBefore;
        }
      });
    };


  });
