class CorpusFileList extends ResourceList {
  static autoInit() {
    for (let corpusFileListElement of document.querySelectorAll('.corpus-file-list:not(.no-autoinit)')) {
      new CorpusFileList(corpusFileListElement);
    }
  }

  constructor(listContainerElement, options = {}) {
    super(listContainerElement, options);
    this.listjs.list.addEventListener('click', (event) => {this.onClick(event)});
    this.isInitialized = false;
    this.userId = listContainerElement.dataset.userId;
    this.corpusId = listContainerElement.dataset.corpusId;
    if (this.userId === undefined || this.corpusId === undefined) {return;}
    app.subscribeUser(this.userId).then((response) => {
      app.socket.on('PATCH', (patch) => {
        if (this.isInitialized) {this.onPatch(patch);}
      });
    });
    app.getUser(this.userId).then((user) => {
      this.add(Object.values(user.corpora[this.corpusId].files || user.followed_corpora[this.corpusId].files));
      this.isInitialized = true;
    });
  }

  get item() {
    return `
      <tr class="list-item clickable hoverable">
        <td><span class="filename"></span></td>
        <td><span class="author"></span></td>
        <td><span class="title"></span></td>
        <td><span class="publishing-year"></span></td>
        <td class="right-align">
          <a class="list-action-trigger btn-floating red waves-effect waves-light" data-list-action="delete"><i class="material-icons">delete</i></a>
          <a class="list-action-trigger btn-floating service-color darken waves-effect waves-light" data-list-action="download" data-service="corpus-analysis"><i class="material-icons">file_download</i></a>
          <a class="list-action-trigger btn-floating service-color darken waves-effect waves-light" data-list-action="view" data-service="corpus-analysis"><i class="material-icons">send</i></a>
        </td>
      </tr>
    `.trim();
  }

  get valueNames() {
    return [
      {data: ['id']},
      {data: ['creation-date']},
      'author',
      'filename',
      'publishing-year',
      'title'
    ];
  }

  initListContainerElement() {
    if (!this.listContainerElement.hasAttribute('id')) {
      this.listContainerElement.id = Utils.generateElementId('corpus-file-list-');
    }
    let listSearchElementId = Utils.generateElementId(`${this.listContainerElement.id}-search-`);
    this.listContainerElement.innerHTML = `
      <div class="input-field">
        <i class="material-icons prefix">search</i>
        <input id="${listSearchElementId}" class="search" type="text"></input>
        <label for="${listSearchElementId}">Search corpus file</label>
      </div>
      <table>
        <thead>
          <tr>
            <th>Filename</th>
            <th>Author</th>
            <th>Title</th>
            <th>Publishing year</th>
            <th></th>
          </tr>
        </thead>
        <tbody class="list"></tbody>
      </table>
      <ul class="pagination"></ul>
    `.trim();
  }

  mapResourceToValue(corpusFile) {
    return {
      'id': corpusFile.id,
      'author': corpusFile.author,
      'creation-date': corpusFile.creation_date,
      'filename': corpusFile.filename,
      'publishing-year': corpusFile.publishing_year,
      'title': corpusFile.title
    };
  }

  sort() {
    this.listjs.sort('creation-date', {order: 'desc'});
  }

  onClick(event) {
    let listItemElement = event.target.closest('.list-item[data-id]');
    if (listItemElement === null) {return;}
    let itemId = listItemElement.dataset.id;
    let listActionElement = event.target.closest('.list-action-trigger[data-list-action]');
    let listAction = listActionElement === null ? 'view' : listActionElement.dataset.listAction;
    switch (listAction) {
      case 'delete': {
        let values = this.listjs.get('id', itemId)[0].values();
        let modalElement = Utils.HTMLToElement(
          `
            <div class="modal">
              <div class="modal-content">
                <h4>Confirm Corpus File deletion</h4>
                <p>Do you really want to delete the Corpus File <b>${values.title}</b>? All files will be permanently deleted!</p>
              </div>
              <div class="modal-footer">
                <a class="btn modal-close waves-effect waves-light">Cancel</a>
                <a class="action-button btn modal-close red waves-effect waves-light" data-action="confirm">Delete</a>
              </div>
            </div>
          `
        );
        document.querySelector('#modals').appendChild(modalElement);
        let modal = M.Modal.init(
          modalElement,
          {
            dismissible: false,
            onCloseEnd: () => {
              modal.destroy();
              modalElement.remove();
            }
          }
        );
        let confirmElement = modalElement.querySelector('.action-button[data-action="confirm"]');
        confirmElement.addEventListener('click', (event) => {
          Requests.corpora.entity.files.ent.delete(this.corpusId, itemId);
        });
        modal.open();
        break;
      }
      case 'download': {
        window.location.href = `/corpora/${this.corpusId}/files/${itemId}/download`;
        break;
      }
      case 'view': {
        window.location.href = `/corpora/${this.corpusId}/files/${itemId}`;
        break;
      }
      default: {
        break;
      }
    }
  }

  onPatch(patch) {
    let re = new RegExp(`^/users/${this.userId}/corpora/${this.corpusId}/files/([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}/corpora/${this.corpusId}/files/([A-Za-z0-9]*)$`);
          if (re.test(operation.path)) {this.add(operation.value);}
          break;
        }
        case 'remove': {
          let re = new RegExp(`^/users/${this.userId}/corpora/${this.corpusId}/files/([A-Za-z0-9]*)$`);
          if (re.test(operation.path)) {
            let [match, corpusFileId] = operation.path.match(re);
            this.remove(corpusFileId);
          }
          break;
        }
        case 'replace': {
          let re = new RegExp(`^/users/${this.userId}/corpora/${this.corpusId}/files/([A-Za-z0-9]*)/(author|filename|publishing_year|title)$`);
          if (re.test(operation.path)) {
            let [match, corpusFileId, valueName] = operation.path.match(re);
            this.replace(corpusFileId, valueName.replace('_', '-'), operation.value);
          }
          break;
        }
        default: {
          break;
        }
      }
    }
  }
}
