angular.module('moduleDataDirective', []).directive('moduleData', [
  'projectsService',
  '$rootScope',
  function (projectsService, $rootScope) {
    return {
      templateUrl: '/build_app/build/partials/modules/input_data',
      restrict: 'A',
      scope: {
        projectId: '=',
        moduleName: '=',
        moduleAdded: '='
      },
      link: function (scope) {
        scope.inputLoaded = false;
        scope.unsupportedType = false;
        projectsService.getModuleInput(scope.projectId, scope.moduleName).then(
          function (response) {
            if (response.data.input_spec.length != 0) {
              scope.input = response.data.input_spec;
              scope.originalInput = angular.copy(scope.input);
            }
            scope.inputLoaded = true;
          },
          () => (scope.inputLoaded = true)
        );

        scope.addResponse = function (itemIndex) {
          if (!scope.input[itemIndex].hasOwnProperty('response')) {
            scope.input[itemIndex].response = [];
          }

          // if subtype is array then we have multiple responses in one item
          // and response should contain them
          if (Array.isArray(scope.input[itemIndex].subtype)) {
            scope.input[itemIndex].response.push(
              scope.input[itemIndex].subtype.reduce((reducer, item) => {
                reducer[item.key] = '';
                return reducer;
              }, {})
            );
          } else {
            // and if subtype is not array then response will be just an array of strings
            scope.input[itemIndex].response.push('');
          }
        };

        scope.setUnsupportedType = function () {
          scope.unsupportedType = true;
        };

        scope.removeResponse = function (itemIndex, responseIndex) {
          scope.input[itemIndex].response.splice(responseIndex, 1);
        };

        scope.save = function () {
          common.globalSpinner.show();
          projectsService.setModuleInput(scope.projectId, scope.moduleName, { input: scope.input }).then(
            () => {
              scope.originalInput = angular.copy(scope.input);
              scope.editInput = false;
              $rootScope.$broadcast('module_data_saved');
              notify.success('Input data successfully saved.');
              common.globalSpinner.hide();
            },
            error => {
              notify.error(error.data.msg || error);
              common.globalSpinner.hide();
            }
          );
        };

        scope.cancel = function () {
          scope.editInput = false;
          scope.input = angular.copy(scope.originalInput);
        };
      }
    };
  }
]);
