/**
 * Created by shadeeka on 12/17/15.
 */

angular.module('app.controllers')
  .filter('checkInprogress', function () {
    return function (object) {
      var visibleUser = false;
      for (var key in object) {
        if (object[key] == true) {
          visibleUser = true;
          break;
        }
      }
      return visibleUser;
    };
  })

  .controller('SystemCtrl', function ($scope, $q, $rootScope, $state, $filter, ionicMaterialInk, $ionicPopup, ionicMaterialMotion, $log, dataPersistenceService, $timeout, sparkDataService, $cordovaFileTransfer, propertyCache, imgSync, $cordovaFile, auditProtocol, LoadingMsg, $interval, initService, $ionicLoading, issuesCache ,updateService,$translate) {
    var ImageLocation = cordova.file.dataDirectory + '/silhouetteList/';
    //var ImageLocation = cordova.file.externalRootDirectory + '/silhouetteList/';

    var _self = this;
    $scope.message = "";
    var syncInProgress = false;
    var checkIntervalInterval = "";
    var retryCount = 0;
    var maxRetryCount = 20;

    var downloadCycles = 0;
    var extractCycles = 0;
    var redirectCycles = 0;

    _self.countryFlag = propertyCache.factoryConfigs.default_language_icon;


    var syncFunction = {
      doneCountSync: false,
      doneReworkSync: false
    };

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

    _self.isBuyerEnable = false;
    if (propertyCache.factoryConfigs.bulk_capturing == "true") {
      _self.isBuyerEnable = true;
    }


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


    _self.synchronise = function () {
      if (propertyCache.networkStatus != "online") {
        var alertPopup = $ionicPopup.alert({
          title: $filter('translate')('ApplicationIsOffline'),
          template: '<div class="nf-center nf-valign-wrapper">' +
          '<ion-spinner icon="ripple" class="nf-text-white"></ion-spinner>' +
          '<span>{{"PleaseCheckYourInternetConnectivity" | translate}} </span></div>'
        });
      } else {


        var id = LoadingMsg.showLoading();
        if ($filter('checkInprogress')(syncFunction)) {
          $ionicPopup.alert({
            title: $filter('translate')('Alert'),
            content: '{{"SyncInProgress" | translate}}'
          }).then(function (res) {
          });
          return;
        }

        $log.debug("Synchronizing counts with remote data");
        $scope.message = "Please wait...";

        var isProcessing1 = false, isProcessing2 = false, isProcessing3 = false,isProcessing4 = false;
        syncFunction.doneCountSync = true;
        sparkDataService.tabChangeSync().then(function (result) {
          _self.setStatus("doneCountSync");
          $rootScope.$broadcast("modelCountUpdate", {type: "sync"});
          isProcessing1 = true;
        }, function (err) {
          _self.setStatus("doneCountSync");
          isProcessing1 = true;
        });

        syncFunction.doneReworkSync = true;
        sparkDataService.unreworkedDefectSync().then(function () {
          _self.setStatus("doneReworkSync");
          isProcessing2 = true;
        }, function () {
          _self.setStatus("doneReworkSync");
          isProcessing2 = true;
        });
        //////////////////audit//////////////////////
        var $audit = auditProtocol.getEvent("syncApp");
        sparkDataService.sendDataToServer($audit)
        /////////////////////////////////////////////////
        $timeout(function () {
          if(propertyCache.factoryConfigs.show_style_info_bar == "true"){
            initService.loadInitialData(true).then(function (result) {
              isProcessing3 = true;
            }, function () {
              isProcessing3 = true;
            });
          }else {
            initService.loadInitialData(false).then(function (result) {
              isProcessing3 = true;
            }, function () {
              isProcessing3 = true;
            });
          }
        }, 5000);

        var line="";
        if(propertyCache.config.lineWithStation!=""){
          line=propertyCache.config.lineWithStation;
        }else{
          line=propertyCache.config.line;
        }
        $timeout(function () {
          sparkDataService.getLineQualityReport(line).then(function (result) {
            isProcessing4 = true;
          }, function () {
            isProcessing4 = true;
          });
        }, 5000);




        var checkInterval = $interval(function () {
          if (isProcessing1 && isProcessing2 && isProcessing3 && isProcessing4) {
            _self.checkImages()
            LoadingMsg.hideLoading(id);
            $interval.cancel(checkInterval);
          }
        }, 1000);
      }

    }

    _self.setStatus = function (type) {
      syncFunction[type] = false;

      if (!$filter('checkInprogress')(syncFunction)) {
        //LoadingMsg.hideLoading();
      }
    }

    _self.syncSessions = function () {
      if (propertyCache.networkStatus != "online") {
        var alertPopup = $ionicPopup.alert({
          title: $filter('translate')('ApplicationIsOffline'),
          template: '<div class="nf-center nf-valign-wrapper">' +
          '<ion-spinner icon="ripple" class="nf-text-white"></ion-spinner>' +
          '<span>{{"PleaseCheckYourInternetConnectivity" | translate}}</span></div>'
        });
      } else {
        var isProcessing1 = false, isProcessing2 = false;
        var id = LoadingMsg.showLoading();
        sparkDataService.getSessionPlans().then(function () {
          isProcessing1 = true;
        }, function () {
          isProcessing1 = true;
        });

        sparkDataService.getSiluhoutteNames().then(function () {
          isProcessing2 = true;
        }, function () {
          isProcessing2 = true;
        });

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

        var checkInterval = $interval(function () {
          if (isProcessing1 && isProcessing2) {
            LoadingMsg.hideLoading(id);
            $interval.cancel(checkInterval);
          }
        }, 1000);
      }

    }

    _self.syncOperations = function () {
      if (propertyCache.networkStatus != "online") {
        var alertPopup = $ionicPopup.alert({
          title: $filter('translate')('ApplicationIsOffline'),
          template: '<div class="nf-center nf-valign-wrapper">' +
          '<ion-spinner icon="ripple" class="nf-text-white"></ion-spinner>' +
          '<span>{{"PleaseCheckYourInternetConnectivity" | translate}}</span></div>'
        });
      } else {
        //remove cached data
        var isProcessing1 = false, isProcessing2 = false, isProcessing3 = false, isProcessing4 = false;
        var id = LoadingMsg.showLoading();
        //remove cached data
        localStorage.removeItem("ops_" + propertyCache.day_start.style.trim());
        localStorage.removeItem("issueList");
        localStorage.removeItem("rejectList");

        sparkDataService.getOperationsForStyles().then(function () {
          isProcessing1 = true;
        }, function () {
          isProcessing1 = true;
        });

        sparkDataService.getIssuesList().then(function () {
          isProcessing2 = true;
        }, function () {
          isProcessing2 = true;
        });

        sparkDataService.getRejectList().then(function () {
          isProcessing3 = true;
        }, function () {
          isProcessing3 = true;
        });

        if (propertyCache.factoryConfigs.bulk_capturing) {
          localStorage.removeItem("sizeList");
          sparkDataService.getBuyerWiseSizeList().then(function (success) {
            $timeout(function () {
              isProcessing4 = true;
              issuesCache.getCartonSizeList();
            }, 10000);
          });
        }

        var checkInterval = $interval(function () {
          if (isProcessing1 && isProcessing2 && isProcessing3 && isProcessing4) {
            //LoadingMsg.hideLoading(id);
            $interval.cancel(checkInterval);
          }
        }, 1000);

        $timeout(function () {
          LoadingMsg.hideLoading(id);
        }, 1000 * 5);

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

    _self.disable = function () {
      $log.debug("Disable app");

      this.showConfirm();

    }

     var changeToEnglish=false;
    _self.changeLanguage = function () {
      $log.debug("changeLanguage app");
      if(!changeToEnglish) {
        $translate.use('en');
        changeToEnglish=true;
        _self.countryFlag="img/uk-flag.png";
      }else{
        if(propertyCache.factoryConfigs.default_language != undefined && propertyCache.factoryConfigs.default_language != "") {
          $translate.use(propertyCache.factoryConfigs.default_language);
          changeToEnglish = false;
          _self.countryFlag=propertyCache.factoryConfigs.default_language_icon;
        }
      }

    }

    // A confirm dialog
    _self.showConfirm = function () {
      var confirmPopup = $ionicPopup.confirm({
        title: $filter('translate')('DisableApplication'),
        template: '{{"AreYouSureYouWantToDisableTheApplication" | translate }} '
      });
      confirmPopup.then(function (res) {
        if (res) {
          dataPersistenceService.disableApp();
          ///////////////////audit//////////////////////
          var $audit = auditProtocol.getEvent("disableApp");
          sparkDataService.sendDataToServer($audit)
          //////////////////////////////////////////////

          window.close();
          ionic.Platform.exitApp();
        } else {
          console.log('You are not sure');
        }
      });
    };
    var sucessSilhouetteList = [];
    var finishedSilhouetteList = [];
    var failSilhouetteList = [];
    var availableSilhouetteList = [];
    var finalSilhouetteList = [];

    _self.syncImages = function () {
      var id = LoadingMsg.showLoading();
      availableSilhouetteList = [];
      window.resolveLocalFileSystemURL(ImageLocation,
        function (fileSystem) {
          var reader = fileSystem.createReader();
          reader.readEntries(
            function (entries) {
              console.log(entries.length);
              angular.forEach(entries,
                function (silihoutteName, key) {
                  /*$cordovaFile.removeFile(ImageLocation, silihoutteName.name).then(function (result) {
                   },
                   function (err) {
                   console.log("Failed to delete file:", JSON.stringify(err));
                   });*/
                  silihoutteName.file(function (fileObj) {
                    if (fileObj.size > 0) {
                      availableSilhouetteList.push(silihoutteName.name.substr(0, silihoutteName.name.length - 4));
                    }
                  });
                });
            },
            function (err) {
              console.log(err);
            });
        });

      $timeout(function () {
        LoadingMsg.hideLoading(id);
        _self.getImages();
      }, 1000 * 10);

    }


    _self.getImages = function () {
      sucessSilhouetteList = [];
      finishedSilhouetteList = [];
      failSilhouetteList = [];
      finalSilhouetteList = [];
      if (propertyCache.networkStatus != "online") {
        var alertPopup = $ionicPopup.alert({
          title: $filter('translate')('ApplicationIsOffline'),
          template: '<div class="nf-center nf-valign-wrapper">' +
          '<ion-spinner icon="ripple" class="nf-text-white"></ion-spinner>' +
          '<span>{{"PleaseCheckYourInternetConnectivity" | translate}}</span></div>'
        });
      } else {

        var factory = propertyCache.config.factory;
        var module = propertyCache.config.line;
        var tenant = propertyCache.config.tenant;


        var trustHosts = true
        var options = {'directory': 'upload'};
        var errorFlag = false;

        //silloutte list to download
        var silhouetteList = imgSync.generateSilhouetteList(propertyCache.siluhouttes.silihoutteNames);

        angular.forEach(silhouetteList, function (silihoutteName, key) {
          var index = availableSilhouetteList.indexOf(silihoutteName);
          if (index == -1) {//if not available add to list
            finalSilhouetteList.push(silihoutteName);
          }
        });

        $timeout(function () {
          if (finalSilhouetteList.length == 0) {
            $ionicLoading.show({
              template: '<div class="nf-center nf-valign-wrapper"><span>{{"NoNewImagesToDownload" | translate}}</span></div>'
            });
            $timeout(function () {
              $ionicLoading.hide();
            }, 1000 * 3);
          }
        }, 1000 * 2);

        angular.forEach(finalSilhouetteList, function (silihoutteName, key) {
          //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 + ".svg";
          var filename = url.split("=").pop();
          var targetPath = ImageLocation + filename;

          $cordovaFileTransfer.download(url, targetPath, options, trustHosts)
            .then(function (result) { // Success!
              console.log("Success " + key + ": " + url);
              sucessSilhouetteList.push(filename);
              finishedSilhouetteList.push(filename);
              imgSync.loadingPopUp(sucessSilhouetteList, finalSilhouetteList, errorFlag);

            }, function (error) { // Error
              console.log("Error " + key + ": " + url);
              finishedSilhouetteList.push(filename);
              failSilhouetteList.push(filename);
              errorFlag = true
              imgSync.loadingPopUp(sucessSilhouetteList, finalSilhouetteList, errorFlag);

            }, function (progress) {
            });
        });

        $timeout(function () {
          _self.checkCompleteInterval(finalSilhouetteList);
        }, 1000 * 60);

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

    _self.checkCompleteInterval = function (finalSilhouetteList) {
      console.log("checkCompleteInterval silhouetteList " + finalSilhouetteList.length);
      console.log("checkCompleteInterval finishedSilhouetteList " + finishedSilhouetteList.length);
      console.log("checkCompleteInterval failSilhouetteList " + failSilhouetteList.length);
      console.log("checkCompleteInterval sucessSilhouetteList " + sucessSilhouetteList.length);
      var _self = this;
      if (checkIntervalInterval != "") {
        $interval.cancel(checkIntervalInterval);
      }
      checkIntervalInterval = $interval(function () {
        retryCount++;
        console.log("checkCompleteInterval ALL " + finalSilhouetteList.length + " Finish " + finishedSilhouetteList.length + " Success " + sucessSilhouetteList.length + " Fail " + failSilhouetteList.length + " retryCount " + retryCount + " maxRetryCount " + maxRetryCount);
        if (finalSilhouetteList.length <= finishedSilhouetteList.length) {
          console.log("checkCompleteInterval condition " + (finalSilhouetteList.length <= finishedSilhouetteList.length));
          console.log("checkCompleteInterval fail " + (failSilhouetteList.length));
          if (failSilhouetteList.length > 0) {//retry
            _self.retryImageDownload(finalSilhouetteList);
            $interval.cancel(checkIntervalInterval);
          }
          if (finalSilhouetteList.length <= sucessSilhouetteList.length) {
            $interval.cancel(checkIntervalInterval);
            imgSync.hidePopUp();
          }
        }
        if (retryCount > maxRetryCount) {
          _self.retryImageDownload(finalSilhouetteList);
          $interval.cancel(checkIntervalInterval);
          retryCount = 0;
        }
      }, 1000 * 10);
    }


    _self.retryImageDownload = function (finalSilhouetteList) {
      console.log("retryImageDownload  " + (failSilhouetteList.length));
      if (failSilhouetteList.length == 0) {
        imgSync.hidePopUp()
      }
      maxRetryCount = 10;
      angular.forEach(failSilhouetteList, function (silihoutteName, key) {
        var url = 'http://' + propertyCache.config.syncIp + '/dataman/getsiluhoutteimage?tenant=' + tenant + '&factory=' + factory + '&siluhoutteName=' + silihoutteName;
        var filename = url.split("=").pop();
        var targetPath = ImageLocation + filename;
        var errorFlag = false;
        var trustHosts = true
        var options = {'directory': 'upload'};

        $cordovaFileTransfer.download(url, targetPath, options, trustHosts)
          .then(function (result) { // Success!
            console.log("Success " + key + ": " + url);
            var index1 = failSilhouetteList.indexOf(filename);
            if (index1 > -1) {
              failSilhouetteList.splice(index1, 1);
            }
            var index2 = finishedSilhouetteList.indexOf(filename);
            if (index2 == -1) {
              finishedSilhouetteList.push(filename);
            }
            var index3 = sucessSilhouetteList.indexOf(filename);
            if (index3 == -1) {
              sucessSilhouetteList.push(filename);
            }
            imgSync.loadingPopUp(sucessSilhouetteList, finalSilhouetteList, errorFlag);

          }, function (error) { // Error
            console.log("Error " + key + ": " + url);
            var index1 = failSilhouetteList.indexOf(filename);
            if (index1 == -1) {
              failSilhouetteList.push(filename);
            }
            var index2 = finishedSilhouetteList.indexOf(filename);
            if (index2 == -1) {
              finishedSilhouetteList.push(filename);
            }
            errorFlag = true;
            imgSync.loadingPopUp(sucessSilhouetteList, finalSilhouetteList, errorFlag);

          }, function (progress) {
          });


        $timeout(function () {
          _self.checkCompleteInterval(finalSilhouetteList);
        }, 1000 * 60);

      });
    }

    _self.syncUsers = function () {
      if (propertyCache.networkStatus != "online") {
        var alertPopup = $ionicPopup.alert({
          title: $filter('translate')('ApplicationIsOffline'),
          template: '<div class="nf-center nf-valign-wrapper">' +
          '<ion-spinner icon="ripple" class="nf-text-white"></ion-spinner>' +
          '<span>{{"PleaseCheckYourInternetConnectivity" | translate}}</span></div>'
        });
      } else {
        localStorage.setItem("isAuthenicationAvailable", false)
        var id = LoadingMsg.showLoading();

        sparkDataService.syncAuthentication().then(function (res) {
          console.log(res)
          LoadingMsg.hideLoading(id);
        }, function (err) {
          var alertPopup = $ionicPopup.alert({
            title: $filter('translate')('SyncingError'),
            template: '<div class="nf-center nf-valign-wrapper">' +
            '<ion-spinner icon="ripple" class="nf-text-white"></ion-spinner>' +
            '<span>{{"PleaseReSyncUsers" | translate}}</span></div>'
          });
          console.log(err)
          LoadingMsg.hideLoading(id);
        })
        //////////////////audit//////////////////////
        var $audit = auditProtocol.getEvent("syncAuthentication");
        sparkDataService.sendDataToServer($audit)
        /////////////////////////////////////////////////
      }
    },

      _self.checkUpdates = function () {
        console.log("Checking Updates !");

        updateService.updateApplication(true);

        // if (propertyCache.networkStatus != "online") {
        //   var alertPopup = $ionicPopup.alert({
        //     title: 'Application is  <b>Offline</b>',
        //     template: '<div class="nf-center nf-valign-wrapper">' +
        //     '<ion-spinner icon="ripple" class="nf-text-white"></ion-spinner>' +
        //     '<span>Please check your internet connectivity</span></div>'
        //   });
        // } else {
        //
        //   var updateMessageWindow = LoadingMsg.showLoading();
        //   if ($filter('checkInprogress')(syncFunction)) {
        //     $ionicPopup.alert({
        //       title: 'Alert',
        //       content: 'Update in progress'
        //     }).then(function (res) {
        //     });
        //     return;
        //   }
        //
        //   var subsResult = false;
        //   var checkResult = false;
        //
        //   // IonicDeploy.init("configData.appType", propertyCache.config.syncIp, function () {
        //   IonicDeploy.init(propertyCache.config.license+"-qc_app", "http://"+propertyCache.config.syncIp, function (result) {
        //   // IonicDeploy.init(propertyCache.config.license+"-qc_app", "http://192.168.1.68:9000", function (result) {
        //     subsResult = result;
        //     console.log("Subscribed ! ",result);
        //   }, function () {
        //     console.log("Init failed !");
        //   })
        //
        //   // if(subsResult == "true"){
        //     IonicDeploy.check(propertyCache.config.license+"-qc_app", "dev", function (result) {
        //       console.log("Success Checked! " ,result);
        //       if(result == "true"){
        //         checkResult = result;
        //         IonicDeploy.download(propertyCache.config.license+"-qc_app", function (dwnloadResult) {
        //           console.log("Downloaded !" + dwnloadResult);
        //           if (dwnloadResult == "true") {
        //             // _self.extractUpdate();
        //
        //             IonicDeploy.extract(propertyCache.config.license+"-qc_app", function (extractResult) {
        //               if (extractResult == "done") {
        //                 console.log("Extracted successfully !" + extractResult);
        //                 LoadingMsg.sendUpdateAcknowledgement();
        //                 _self.redirectApp();
        //               }
        //             }, function () {
        //               console.log("Extracted faliure !");
        //             });
        //
        //           }
        //         }, function () {
        //           console.log("Download failed !");
        //         });
        //       }else{
        //         LoadingMsg.hideLoading(updateMessageWindow);
        //         var alertPopup = $ionicPopup.alert({
        //           title: 'Info !',
        //           template: '<div class="nf-center nf-valign-wrapper">' +
        //           '<ion-spinner icon="ripple" class="nf-text-white"></ion-spinner>' +
        //           '<span>No Updates !</span></div>'
        //         });
        //       }
        //     }, function () {
        //       console.log("Check failed !");
        //     });
        //   // }
        //
        //   var checkInterval = $interval(function () {
        //     // if (isProcessingUpdate) {
        //     LoadingMsg.hideLoading(updateMessageWindow);
        //     $interval.cancel(checkInterval);
        //     // }
        //   }, 10000);
        //
        // }

      }

    // _self.extractUpdate = function () {
    //   var isProcessingExtract = true;
    //   console.log("Extracted response ");
    //   IonicDeploy.extract(propertyCache.config.license+"-qc_app", function (result) {
    //     if (result == "done") {
    //       console.log("Extracted successfully !" + result);
    //       sparkDataService.sendUpdateAcknowledgement();
    //       _self.redirectApp();
    //     }
    //   }, function () {
    //     console.log("Extracted faliure !");
    //   });
    // }

    // _self.redirectApp = function () {
    //   IonicDeploy.redirect(propertyCache.config.license+"-qc_app", function () {
    //
    //     var checkInterval = $interval(function () {
    //       LoadingMsg.hideLoading(id);
    //       $interval.cancel(checkInterval);
    //     }, 3000);
    //
    //   }, function () {
    //     console.log("Redirected failed !");
    //   });
    // }

    $scope.$on('$ionicView.beforeEnter', function () {
      $scope.$parent.clearAllFabs();
    });

  });
