class TesseractOCRPipelineModelList extends ResourceList {
  static autoInit() {
    for (let tesseractOCRPipelineModelListElement of document.querySelectorAll('.tesseract-ocr-pipeline-model-list:not(.no-autoinit)')) {
      new TesseractOCRPipelineModelList(tesseractOCRPipelineModelListElement);
    }
  }

  constructor(listContainerElement, options = {}) {
    super(listContainerElement, options);
    this.listjs.list.addEventListener('change', (event) => {this.onChange(event)});
    this.listjs.list.addEventListener('click', (event) => {this.onClick(event)});
    this.isInitialized = false;
    this.userId = listContainerElement.dataset.userId;
    if (this.userId === 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.tesseract_ocr_pipeline_models));
      for (let uncheckedCheckbox of this.listjs.list.querySelectorAll('input[data-checked="True"]')) {
        uncheckedCheckbox.setAttribute('checked', '');
      }
      if (user.role.name !== ('Administrator' || 'Contributor')) {
        for (let switchElement of this.listjs.list.querySelectorAll('.is_public')) {
          switchElement.setAttribute('disabled', '');
        }
      }
      this.isInitialized = true;
    });
  }

  get item() {
    return (values) => {
      return `
        <tr class="list-item clickable hoverable">
          <td><b><span class="title"></span> <span class="version"></span></b><br><i><span class="description"></span></i></td>
          <td><a class="publisher-url"><span class="publisher"></span></a> (<span class="publishing-year"></span>)<br><a class="publishing-url"><span class="publishing-url-2"></span></a></td>
          <td>
            <span class="disable-on-click">
              <label>
                <input ${values['is-public'] ? 'checked' : ''} class="is-public list-action-trigger" data-list-action="toggle-is-public" type="checkbox">
                <span>Public</span>
              </label>
            </span>
          </td>
          <td class="right-align">
            <a class="list-action-trigger btn-floating red waves-effect waves-light" data-list-action="delete-request"><i class="material-icons">delete</i></a>
            <a class="list-action-trigger btn-floating service-color darken waves-effect waves-light service-2" data-list-action="view"><i class="material-icons">send</i></a>
          </td>
        </tr>
      `.trim();
    };
  }

  get valueNames() {
    return [
      {data: ['id']},
      {data: ['creation-date']},
      {name: 'publisher-url', attr: 'href'},
      {name: 'publishing-url', attr: 'href'},
      'description',
      'publisher',
      'publishing-url-2',
      'publishing-year',
      'title',
      'title-2',
      'version',
      {name: 'is_public', attr: 'data-checked'}
    ];
  }

  initListContainerElement() {
    if (!this.listContainerElement.hasAttribute('id')) {
      this.listContainerElement.id = Utils.generateElementId('tesseract-ocr-pipeline-model-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 Tesseract OCR Pipeline Model</label>
      </div>
      <table>
        <thead>
          <tr>
            <th>Title and Description</th>
            <th>Publisher</th>
            <th>Availability</th>
            <th></th>
          </tr>
        </thead>
        <tbody class="list"></tbody>
      </table>
      <ul class="pagination"></ul>
    `.trim();
  }

  mapResourceToValue(tesseractOCRPipelineModel) {
    return {
      'id': tesseractOCRPipelineModel.id,
      'creation-date': tesseractOCRPipelineModel.creation_date,
      'description': tesseractOCRPipelineModel.description,
      'publisher': tesseractOCRPipelineModel.publisher,
      'publisher-url': tesseractOCRPipelineModel.publisher_url,
      'publishing-url': tesseractOCRPipelineModel.publishing_url,
      'publishing-url-2': tesseractOCRPipelineModel.publishing_url,
      'publishing-year': tesseractOCRPipelineModel.publishing_year,
      'title': tesseractOCRPipelineModel.title,
      'title-2': tesseractOCRPipelineModel.title,
      'version': tesseractOCRPipelineModel.version,
      'is-public': tesseractOCRPipelineModel.is_public
    };
  }

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

  onChange(event) {
    if (event.target.tagName !== 'INPUT') {return;}
    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]');
    if (listActionElement === null) {return;}
    let listAction = listActionElement.dataset.listAction;
    switch (listAction) {
      case 'toggle-is-public': {
        let newIsPublicValue = listActionElement.checked;
        Requests.contributions.tesseract_ocr_pipeline_models.entity.isPublic.update(itemId, newIsPublicValue)
          .catch((response) => {
            listActionElement.checked = !newIsPublicValue;
          });
        break;
      }
      default: {
        break;
      }
    }
  }

  onClick(event) {
    if (event.target.closest('.disable-on-click') !== null) {return;}
    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]');
    // ignore switch clicks, handle them by the onChange method instead
    if (listActionElement.classList.contains('switch')) {
      event.preventDefault();
      this.onChange(event);
    }
    let listAction = listActionElement === null ? 'view' : listActionElement.dataset.listAction;
    switch (listAction) {
      case 'delete-request': {
        let values = this.listjs.get('id', itemId)[0].values();
        let modalElement = Utils.HTMLToElement(
          `
            <div class="modal">
              <div class="modal-content">
                <h4>Confirm Tesseract OCR Pipeline Model deletion</h4>
                <p>Do you really want to delete the Tesseract OCR Pipeline Model <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.contributions.tesseract_ocr_pipeline_models.entity.delete(itemId);
        });
        modal.open();
        break;
      }
      case 'view': {
        window.location.href = `/contributions/tesseract-ocr-pipeline-models/${itemId}`;
        break;
      }
      default: {
        break;
      }
    }
  }

  onPatch(patch) {
    let re = new RegExp(`^/users/${this.userId}/tesseract_ocr_pipeline_models/([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}/tesseract_ocr_pipeline_models/([A-Za-z0-9]*)$`);
          if (re.test(operation.path)) {this.add(operation.value);}
          break;
        }
        case 'remove': {
          let re = new RegExp(`^/users/${this.userId}/tesseract_ocr_pipeline_models/([A-Za-z0-9]*)$`);
          if (re.test(operation.path)) {
            let [match, itemId] = operation.path.match(re);
            this.remove(itemId);
          }
          break;
        }
        case 'replace': {
          let re = new RegExp(`^/users/${this.userId}/tesseract_ocr_pipeline_models/([A-Za-z0-9]*)/(is_public)$`);
          if (re.test(operation.path)) {
            let [match, itemId, valueName] = operation.path.match(re);
            if (valueName === 'is_public') {
              this.listjs.list.querySelector(`.list-item[data-id="${itemId}"] .is-public`).checked = operation.value;
              valueName = 'is-public';
            }
            this.replace(itemId, valueName, operation.value);
          }
          break;
        }
        default: {
          break;
        }
      }
    }
  }
}
