'use strict';
define(function() {
  var formBuilderFunction = function(ngDialog, gcformfunction, $rootScope) {
    return {
      templateUrl:
        'js/XG/widgets/utilities/form/views/formBuilderFunction.html',
      restrict: 'EA',
      scope: {
        res: '=',
        label: '@',
        isBeforeFinish: '=?',
        isFinish: '=?'
      },
      link: function(scope, element, attrs, ctrl) {
        scope.infos = { label: 'functions' };
        if (angular.isDefined(scope.label)) scope.infos.label = scope.label;

        scope.myfct = {};
        scope.functionslst = gcformfunction.getfunctions();

        scope.eventFunctions = {};

        scope.eventFunctions.lines = angular.isArray(scope.res)
          ? scope.res
          : [];

        console.log(scope.eventFunctions);

        /**
         * Add a line
         */
        scope.addLine = function() {
          if (scope.myfct.hasOwnProperty('template')) {
            scope.eventFunctions.lines.push(scope.myfct.template);
          }
        };

        /**
         * Delete a line
         * @param index
         */
        scope.deleteLine = function(index) {
          scope.eventFunctions.lines.splice(index, 1);
        };

        /**
         * Update res
         */
        scope.$watch(
          'eventFunctions',
          function(eventFunctions) {
            scope.displayFunctions = [];
            eventFunctions.lines.forEach(function(func) {
              var pos_ouv = func.indexOf('(');
              var functionName = func.substring(0, pos_ouv).trim();
              let pos_fer = func.lastIndexOf(')');
              var argsStr = func.substring(pos_ouv + 1,pos_fer);
              var funcDesc = {
                label: functionName,
                parameters: [],
              };

              argsStr.split(',').forEach(function(arg) {
                // object
                if (arg.indexOf('kisbuilderobj#') == 0) {
                  funcDesc.parameters.push('kis objet');
                  // string
                } else {
                  funcDesc.parameters.push(arg);
                }
              });
              scope.displayFunctions.push(funcDesc);
            });
            // isBeforeFinish et isFinish sont des boolean définis quand il s'agit des fonctions
            // du bouton global "Enregistrer" de l'IS
            // ils permettent de distinguer si ce composant concerne les fonctions bfinish ou finish du bouton
            if (scope.isBeforeFinish){
              // envoi au formBuilder
              scope.$emit('globalSaveBeforeFinish', eventFunctions.lines);
            }else if (scope.isFinish){
              // envoi au formBuilder
              scope.$emit('globalSaveFinish', eventFunctions.lines);
            }else{
              scope.res = eventFunctions.lines;
            }
          },
          1
        );

        /**
         * Open the formFunctionsBrowser
         * @param index
         */
        scope.openFunctionsBrowser = function(index) {
          scope.openIndex = index || 0;
          scope.formInfo = $rootScope.currentlyEditedForm;
          ngDialog.open({
            template:
              'js/XG/widgets/utilities/form/views/modal/modal.functionsbrowser.html',
            className: 'ngdialog-theme-plain fullScreen nopadding miniclose',
            closeByDocument: false,
            scope: scope,
            showClose: false,
          });
        };
      },
    };
  };

  formBuilderFunction.$inject = ['ngDialog', 'gcformfunction', '$rootScope'];
  return formBuilderFunction;
});
