import { esc, formatWhen, stripTags } from './utils.js';

export function renderNoteList(listEl, options) {
  if (!listEl) return;
  options = options || {};
  var pane = options.pane || 'active';
  var search = options.search || '';
  var source = pane === 'trash' ? (options.trash || []) : (options.notes || []);
  var filtered = source;

  if (search) {
    filtered = source.filter(function(n) {
      var hay = ((n.title || '') + ' ' + stripTags(n.body || '')).toLowerCase();
      return hay.indexOf(search) !== -1;
    });
  }

  if (filtered.length === 0) {
    listEl.innerHTML = '<div class="notes-empty">'
      + (search ? 'No matches' : (pane === 'trash' ? 'Trash is empty' : ''))
      + '</div>';
    return;
  }

  listEl.innerHTML = filtered.map(function(n) {
    var snippet = stripTags(n.body || '').substring(0, 110);
    var when = formatWhen(pane === 'trash' ? n.deleted_at : n.updated_at);
    var active = (n.id === options.activeId && pane === 'active') ? ' active' : '';
    var trashActions = pane === 'trash'
      ? '<div class="notes-trash-actions">'
          + '<button type="button" class="notes-restore-btn" data-id="' + n.id + '" title="Restore">'
          +   '<i class="fas fa-rotate-left"></i> Restore'
          + '</button>'
          + '<button type="button" class="notes-hard-delete-btn" data-id="' + n.id + '" title="Delete forever">'
          +   '<i class="fas fa-times"></i>'
          + '</button>'
        + '</div>'
      : '';
    return '<div class="notes-list-row">'
      +   '<button type="button" class="notes-list-item' + active + '" data-id="' + n.id + '">'
      +     '<div class="notes-list-title">' + esc(n.title || 'Untitled') + '</div>'
      +     '<div class="notes-list-snippet">' + esc(snippet) + '</div>'
      +     '<div class="notes-list-when">'
      +       (pane === 'trash' ? 'Deleted ' : '') + esc(when)
      +     '</div>'
      +   '</button>'
      +   trashActions
      + '</div>';
  }).join('');
}

export function updateTrashCount(el, trashCount) {
  if (!el) return;
  el.textContent = trashCount ? '(' + trashCount + ')' : '';
}
