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

  constructor(listContainerElement, options = {}) {
    super(listContainerElement, options);
    this.listjs.on('updated', () => {
      M.FormSelect.init(this.listjs.list.querySelectorAll('.list-item select'));
    });
    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;
    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].corpus_follower_associations));
      this.isInitialized = true;
    });
  }

  get item() {
    return (values) => {
      return `
        <tr class="list-item clickable hoverable">
          <td><img alt="follower-avatar" class="circle responsive-img follower-avatar" style="width:50%"></td>
          <td><b class="follower-username"><b></td>
          <td>
            <span class="follower-full-name"></span>
            <br>
            <i class="follower-about-me"></i>
          </td>
          <td>
            <div class="input-field disable-on-click list-action-trigger" data-list-action="update-role">
              <select>
                <option value="Viewer" ${values['role-name'] === 'Viewer' ? 'selected' : ''}>Viewer</option>
                <option value="Contributor" ${values['role-name'] === 'Contributor' ? 'selected' : ''}>Contributor</option>
                <option value="Administrator" ${values['role-name'] === 'Administrator' ? 'selected' : ''}>Administrator</option>
              </select>
            </div>
          </td>
          <td class="right-align">
            <a class="list-action-trigger btn-floating red waves-effect waves-light" data-list-action="unfollow-request"><i class="material-icons">delete</i></a>
            <a class="list-action-trigger btn-floating darken waves-effect waves-light" data-list-action="view"><i class="material-icons">send</i></a>
          </td>
        </tr>
      `.trim();
    }
  }

  get valueNames() {
    return [
      {data: ['id']},
      {data: ['follower-id']},
      {name: 'follower-avatar', attr: 'src'},
      'follower-username',
      'follower-about-me',
      'follower-full-name'
    ];
  }

  initListContainerElement() {
    if (!this.listContainerElement.hasAttribute('id')) {
      this.listContainerElement.id = Utils.generateElementId('corpus-follower-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 follower</label>
      </div>
      <table>
        <thead>
          <tr>
            <th style="width:15%;"></th>
            <th>Username</th>
            <th>User details</th>
            <th>Role</th>
            <th></th>
          </tr>
        </thead>
        <tbody class="list"></tbody>
      </table>
      <ul class="pagination"></ul>
    `.trim();
  }

  mapResourceToValue(corpusFollowerAssociation) {
    return {
      'id': corpusFollowerAssociation.id,
      'follower-id': corpusFollowerAssociation.follower.id,
      'follower-avatar': corpusFollowerAssociation.follower.avatar ? `/users/${corpusFollowerAssociation.follower.id}/avatar` : '/static/images/user_avatar.png',
      'follower-username': corpusFollowerAssociation.follower.username,
      'follower-full-name': corpusFollowerAssociation.follower.full_name ? corpusFollowerAssociation.follower.full_name : '',
      'follower-about-me': corpusFollowerAssociation.follower.about_me ? corpusFollowerAssociation.follower.about_me : '',
      'role-name': corpusFollowerAssociation.role.name
    };
  }

  sort() {
    this.listjs.sort('username', {order: 'desc'});
  }

  onChange(event) {
    console.log(event.target.tagName);
    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 'update-role': {
        let followerId = listItemElement.dataset.followerId;
        let roleName = event.target.value;
        Requests.corpora.entity.followers.entity.role.update(this.corpusId, followerId, roleName);
        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]');
    let listAction = listActionElement === null ? 'view' : listActionElement.dataset.listAction;
    switch (listAction) {
      case 'unfollow-request': {
        let followerId = listItemElement.dataset.followerId;
        Requests.corpora.entity.followers.entity.delete(this.corpusId, followerId);
        break;
      }
      case 'view': {
        let followerId = listItemElement.dataset.followerId;
        window.location.href = `/users/${followerId}`;
        break;
      }
      default: {
        break;
      }
    }
  }

  onPatch(patch) {
    let re = new RegExp(`^/users/${this.userId}/corpora/${this.corpusId}/corpus_follower_associations/([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}/corpus_follower_associations/([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}/corpus_follower_associations/([A-Za-z0-9]*)$`);
          if (re.test(operation.path)) {
            let [match, jobId] = operation.path.match(re);
            this.remove(jobId);
          }
          break;
        }
        case 'replace': {
          let re = new RegExp(`^/users/${this.userId}/corpora/${this.corpusId}/corpus_follower_associations/([A-Za-z0-9]*)/role$`);
          if (re.test(operation.path)) {
            console.log('role updated');
            let [match, jobId, valueName] = operation.path.match(re);
            this.replace(jobId, valueName, operation.value);
          }
          break;
        }
        default: {
          break;
        }
      }
    }
  }
}
