class JobResultList extends RessourceList {
  static options = {
    item: `
      <tr class="hoverable">
        <td><span class="description"></span></td>
        <td><span class="filename"></span></td>
        <td class="right-align">
          <a class="action-button btn-floating tooltipped waves-effect waves-light" data-action="download" data-position="top" data-tooltip="View"><i class="material-icons">file_download</i></a>
        </td>
      </tr>
    `.trim(),
    ressourceMapper: jobResult => {
      let description;

      if (jobResult.filename.endsWith('.pdf.zip')) {
        description = 'PDF files with text layer';
      } else if (jobResult.filename.endsWith('.txt.zip')) {
        description = 'Raw text files';
      } else if (jobResult.filename.endsWith('.vrt.zip')) {
        description = 'VRT compliant files including the NLP data';
      } else if (jobResult.filename.endsWith('.xml.zip')) {
        description = 'TEI compliant files';
      } else if (jobResult.filename.endsWith('.poco.zip')) {
        description = 'HOCR and image files for post correction (PoCo)';
      } else {
        description = 'All result files created during this job';
      }
      return {
        id: jobResult.id,
        creationDate: jobResult.creation_date,
        description: description,
        filename: jobResult.filename
      };
    },
    sortValueName: 'creationDate',
    valueNames: [
      {data: ['id']},
      {data: ['creationDate']},
      '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 action;
    let actionButtonElement;
    let jobResultElement;
    let jobResultId;

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

  usersPatchHandler(patch) {
    let filteredPatch;
    let operation;
    let re;

    re = new RegExp(`^/users/${this.userId}/jobs/${this.jobId}/results/([A-Za-z0-9]*)`);
    filteredPatch = patch.filter(operation => re.test(operation.path));
    for (operation of filteredPatch) {
      switch(operation.op) {
        case 'add':
          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;
      }
    }
  }
}