'use strict';
define(function() {
  var LocalParametersCtrl = function(
    $scope,
    ParametersFactory,
    ngDialog,
    $location,
    SirocoFactory,
    $rootScope
  ) {
    $scope.checkCurrentParam1 = function() {
      $scope.prevCheckTime = $scope.checkTime;
      $scope.checkTime = Date.now();
      var d = $scope.checkTime - $scope.prevCheckTime;
      console.log('d=' + d);
      if (d > 449) {
        console.log('executer');
        $scope.checkCurrentParamReel();
        $scope.checkTime = undefined;
      } else {
        console.log('$scope.checkTime==undefined');
        setTimeout($scope.checkCurrentParam1, 450);
      }
    };

    $scope.checkCurrentParam = function(newval, oldval) {
      if ($scope.checkTime == undefined) {
        $scope.checkTime = Date.now();
        setTimeout(function() {
          $scope.checkCurrentParam1(undefined, undefined, true);
        }, 450);
        return;
      }
      $scope.checkTime = Date.now();
    };
    /*
        $scope.checkCurrentParam = function(newval,oldval)
        {
         if (newval!=undefined && newval==oldval) return;
         $scope.prevCheckTime = $scope.checkTime;
         $scope.checkTime = Date.now();
         //console.log("$scope.checkTime-$scope.prevCheckTime: "+($scope.checkTime-$scope.prevCheckTime));

         var diff;
         if ($scope.prevCheckTime!=undefined)
            {
             diff = $scope.checkTime-$scope.prevCheckTime;
             if (diff<50)  return;
            }
         if (newval!=undefined 
          || ($scope.prevCheckTime==undefined || diff<600 || diff>20000)
            )
            {
             //console.log("settimeout 1");
             setTimeout($scope.checkCurrentParam,600);
            }
         else
            {
             //console.log("exec ?  $scope.checkTime-$scope.lastCheckTime: "+($scope.checkTime-$scope.lastCheckTime));
             //if ($scope.prevCheckTime==undefined || $scope.checkTime-$scope.lastCheckTime>1500)
                 //$scope.checkCurrentParamReel();
                 setTimeout($scope.checkCurrentParamReel,300);
                 /*
             else
                {
                 console.log("settimeout 2");
             //    setTimeout($scope.checkCurrentParam,1501);
                }*
             $scope.lastCheckTime = Date.now();
            }
        };
*/
    $scope.checkCurrentParamReel = function() {
      if ($scope.currentParametrage === false) return;
      var params = $scope.currentParametrage.data.parametres;
      var ind, param, iLine, iCol;

      $scope.currentParametrage.changes++;
      console.log(
        'checkCurrentParamReel: ' + $scope.currentParametrage.changes
      );
      $scope.currentParametrageNotComplete = false;
      if (params == undefined) {
        $scope.currentParametrageNotComplete = true;
        return;
      }
      for (ind = 0; ind < params.length; ind++) {
        param = params[ind];
        param.completeStyle = 'none';
        if (param.type_parametre == null) continue;
        if (param.Type == 'valeur') {
          if (param.Valeur == null || param.Valeur == '') {
            $scope.currentParametrageNotComplete = true;
            param.completeStyle = 'parameterIsNotComplete';
            //break;
          } else param.Valeur = parseInt(param.Valeur);
        } else if (param.Type == 'liste') {
          for (iLine = 0; iLine < param.ListeValeurs.length; iLine++) {
            if (param.ListeValeurs[iLine] == null) {
              $scope.currentParametrageNotComplete = true;
              param.completeStyle = 'parameterIsNotComplete';
              break;
            }
          }
        } else if (param.Type == 'tableau') {
          for (iLine = 0; iLine < param.TableauValeurs.length; iLine++) {
            for (iCol = 0; iCol < param.TableauValeurs[iLine].length; iCol++) {
              if (param.TableauValeurs[iLine][iCol] == null) {
                $scope.currentParametrageNotComplete = true;
                param.completeStyle = 'parameterIsNotComplete';
                break;
              }
            }
          }
        }
      }
      $rootScope.$broadcast('sirocoRefreshParamsList');
    };

    $scope.setWatchOnFields = function() {
      if ($scope.currentParametrage.data == undefined) return;
      var params = $scope.currentParametrage.data.parametres;
      var ind, param, iLine, iCol, pStr;

      for (ind = 0; ind < params.length; ind++) {
        param = params[ind];
        if (param.type_parametre == null) continue;
        pStr = 'currentParametrage.data.parametres[' + ind + ']';
        if (param.Type == 'valeur') {
          $scope.$watch(pStr + '.Valeur', $scope.checkCurrentParam);
        } else if (param.Type == 'liste') {
          for (iLine = 0; iLine < param.ListeValeurs.length; iLine++) {
            $scope.$watch(
              pStr + '.ListeValeurs[' + iLine + ']',
              $scope.checkCurrentParam
            );
          }
        } else if (param.Type == 'tableau') {
          for (iLine = 0; iLine < param.TableauValeurs.length; iLine++) {
            for (iCol = 0; iCol < param.TableauValeurs[iLine].length; iCol++) {
              $scope.$watch(
                pStr + '.TableauValeurs[' + iLine + '][' + iCol + ']',
                $scope.checkCurrentParam
              );
            }
          }
        }
      }
    };

    $scope.defineWatchers = function() {
      if ($scope.currentParametrage == undefined)
        setTimeout($scope.defineWatchers, 850);
      else {
        var params = $scope.currentParametrage.data.parametres;

        if (params == undefined || params.length == 0) {
          $scope.currentParametrage.data.parametres = [];
          $scope.$watch(
            'currentParametrage.data.parametres',
            $scope.setWatchOnFields
          );
        } else $scope.setWatchOnFields();
      }
    };

    /*
        $scope.defineWatchers = function()
        {
            setTimeout( $scope.defineWatchersTo,2000);
        };
*/
    $scope.currentParametrage = false;
    $scope.currentParametrageNotComplete = false;
    var sirocoCfg = JSON.parse(sessionStorage.getItem('sirocoCfg'));

    $scope.$watch('currentParametrage', function(currentParametrage) {
      console.log(currentParametrage);
      if ($scope.currentParametrage === false) return;
      $scope.currentParametrageNotComplete = false;
      $scope.currentParametrage.changes = 0;
      $scope.checkCurrentParam();
      $scope.defineWatchers();
    });

    /**
     * load the list of cfg
     */
    $scope.loadCfgList = function() {
      $scope.currentParametrage = false;
      $scope.cfgList = [];
      ParametersFactory.getbytype('siroco_corpshypo').then(function(res) {
        if (res.data.length > 0) {
          var ii = 0;
          var ok = 0;
          res.data.forEach(function(cfg) {
            if (cfg.data.app == sirocoCfg.appuid) {
              ok++;
            }
          });
          res.data.forEach(function(cfg) {
            if (cfg.data.app == sirocoCfg.appuid) {
              {
                $scope.cfgList.push(cfg);
                if (ok == 1 && ii++ == 0) {
                  $scope.currentParametrage = cfg;
                  $scope.checkCurrentParam();
                }
              }
            }
          });
        }
      });
    };

    $scope.loadCfgList();
    /**
     * newParametrageModal
     */
    $scope.newParametrageModal = function() {
      $scope.newParametrageData = {};
      ngDialog.open({
        template:
          'js/XG/widgets/sirocoapp/init/views/modals/modal.newparametrage.html',
        className: 'ngdialog-theme-plain nopadding miniclose',
        closeByDocument: false,
        scope: $scope,
      });
    };
    /**
     * newParametrage
     */
    $scope.newParametrage = function() {
      var sirocoCfg = JSON.parse(sessionStorage.getItem('sirocoCfg'));
      var saveData = {
        app: sirocoCfg.appuid,
      };

      SirocoFactory.getemptych(sirocoCfg.appname).then(function(res) {
        console.log(res.data);
        if (res.data.ok) {
          saveData.parametres = res.data.valeur.Parametres;
          ParametersFactory.add(
            saveData,
            'siroco_corpshypo',
            $scope.newParametrageData.name
          ).then(function(res) {
            $scope.cfgList.push(res.data);
            $scope.currentParametrage = res.data;
            $scope.defineWatchers();
          });
        } else {
          require('toastr').error(
            res.data.errorMessage,
            'Erreur dans lors du la récupération du paramétrage',
            {
              closeButton: true,
              timeOut: '0',
              extendedTimeOut: '0',
              positionClass: 'toast-bottom-full-width',
            }
          );
        }
      });
    };

    $scope.tabs = [
      {
        title: 'siroco.navigation.init.local_parameters',
        content: 'js/XG/widgets/sirocoapp/init/views/local_parameters.html',
      },
      {
        title: 'siroco.navigation.init.expert_parameters',
        content: 'js/XG/widgets/sirocoapp/init/views/expert_parameters.html',
      },
    ];
    $scope.tabs.activeTab = 0;
  };

  LocalParametersCtrl.$inject = [
    '$scope',
    'ParametersFactory',
    'ngDialog',
    '$location',
    'SirocoFactory',
    '$rootScope',
  ];
  return LocalParametersCtrl;
});
