export default function dynamicInput() {
  return {
    restrict: 'E',
    templateUrl: '/js/xivo/directives/dynamic-input.html',
    scope: {
      name: '@',
      placeholder: '@',
      inputs: '=',
      error: '=',
      columns: '=',
      init: '='
    },
    link: (scope) => {
      scope.showAllInputs = false;

      const getMaxId = () => {
        if (!scope.inputs) return 0;
        return Math.max(...scope.inputs.map(i => i.id), 0);
      };

      scope.addNewInput = () => {
        let input = {id : getMaxId()+1};
        for (const key of scope.columns) {
          input[key.name] = null;
        }
        scope.inputs.push(input);
      };

      scope.removeInput = (input) => {
        if ( scope.inputs.length-1 > 0 ) {
          scope.inputs = scope.inputs.filter((i) => i.id !== input.id);
        }
      };

      scope.showAddInput = (input) => {
        return input.id === getMaxId();
      };

      if (scope.init) scope.addNewInput();
    }
  };
}
