class JobResultList extends RessourceList {
  static autoInit() {
    for (let jobResultListElement of document.querySelectorAll('.job-result-list:not(.no-autoinit)')) {
      new JobResultList(jobResultListElement);
    }
  }

  static options = {
    initialHtmlGenerator: (id) => {
      return `
        <div class="input-field">
          <i class="material-icons prefix">search</i>
          <input id="${id}-search" class="search" type="search"></input>
          <label for="${id}-search">Search job result</label>
        </div>
        <table>
          <thead>
            <tr>
              <th>Description</th>
              <th>Filename</th>
              <th></th>
            </tr>
          </thead>
          <tbody class="list"></tbody>
        </table>
        <ul class="pagination"></ul>
      `.trim();
    },
    item: `
      <tr class="clickable hoverable">
        <td><span class="description"></span></td>
        <td><span class="filename"></span></td>
        <td class="right-align">
          <a class="action-button btn-floating waves-effect waves-light" data-action="download"><i class="material-icons">file_download</i></a>
        </td>
      </tr>
    `.trim(),
    ressourceMapper: (jobResult) => {
      return {
        'id': jobResult.id,
        'creation-date': jobResult.creation_date,
        'description': jobResult.description,
        'filename': jobResult.filename
      };
    },
    sortArgs: ['filename', {order: 'asc'}],
    valueNames: [
      {data: ['id']},
      {data: ['creation-date']},
      'description',
      'filename'
    ]
  };

  constructor(listElement, options = {}) {
    super(listElement, {...JobResultList.options, ...options});
    this.jobId = listElement.dataset.jobId;
  }

  init(user) {
    super._init(user.jobs[this.jobId].results);
  }

  onClick(event) {
    let actionButtonElement = event.target.closest('.action-button');
    let action = actionButtonElement === null ? 'download' : actionButtonElement.dataset.action;
    let jobResultElement = event.target.closest('tr');
    let jobResultId = jobResultElement.dataset.id;
    switch (action) {
      case 'download': {
        window.location.href = `/jobs/${this.jobId}/results/${jobResultId}/download`;
        break;
      }
      default: {
        break;
      }
    }
  }

  onPatch(patch) {
    let re = new RegExp(`^/users/${this.userId}/jobs/${this.jobId}/results/([A-Za-z0-9]*)`);
    let filteredPatch = patch.filter(operation => re.test(operation.path));
    for (let operation of filteredPatch) {
      switch(operation.op) {
        case 'add': {
          let re = new RegExp(`^/users/${this.userId}/jobs/${this.jobId}/results/([A-Za-z0-9]*)$`);
          if (re.test(operation.path)) {this.add(operation.value);}
          break;
        }
        default: {
          break;
        }
      }
    }
  }
}
