<table id="booktable" class="table dataTable stripe">
  <thead>
    <tr>
      <th width="40%">Title</th>
      <th>Language</th>
      <th>Tags</th>
      <th>Word count (% known)</th>
      <th>Actions</th>
    </tr>
  </thead>
</table>

{# Hidden form for archive, unarchive, delete. #}
<form id="actionposter" method="post" action="">
</form>

<script>
  
  let setup_text_datatable = function(initial_search) {
    var table = $('#booktable').DataTable({
      {% if status != 'Archived' %}
      "language": {
            "emptyTable": "No books available. <a href='/book/new'>Create one?</a>"
      },
      {% endif %}
      responsive: true,
      select: true,
      lengthMenu: [ 10, 25, 50 ],
      paging: true,
      info: true,
      searching: true,
      processing: true,
      serverSide: true,
      search: { search: initial_search },
      columnDefs: [
        {
          "name": "BkTitle", "targets": 0,
          "render": function ( data, type, row, meta ) {
            const bkid = parseInt(row[3]);
            const pgnum = parseInt(row[10]);
            const pgcount = parseInt(row[8]);
            let pgfraction = '';
            if (pgnum > 1) {
              pgfraction = ` (${pgnum}/${pgcount})`;
            }
            return `<a href="/read/${bkid}/page/${pgnum}">${row[0]}${pgfraction}</a>`;
          }
        },
        { "name": "LgName", "targets": 1 },
        { "name": "TagList", "targets": 2 },

        { "targets": 3,
          "data": null,
          "searchable": false,
          "orderable": false,
          "render": function ( data, type, row, meta ) {
            let ret = row[5];
            const pct = row[7];
            const unkcount = row[6];
            if (pct != null) {
              const termcount = row[9];
              const knownpct = 100 - parseInt(pct);
              ret += `&nbsp;<span title="${unkcount} unknowns in next ${termcount} unique terms">(${knownpct}%)</span>`;
            }
            return ret;
          }
        },
        {
          "targets": 4,
          "data": null,
          "searchable": false,
          "orderable": false,
          "render": function ( data, type, row, meta ) {
            // TODO zzfuture fix: security - add CSRF token
            const ret = [];
            const bkid = row[3];
            if (row[4] == 0) {
              // not archived
              ret.push(`<img src="{{ url_for('static', filename='icn/document--pencil.png') }}" title="Edit" onclick="edit_book(${bkid})" />`);
              ret.push(`<img src="{{ url_for('static', filename='icn/inbox-download.png') }}" title="Archive" onclick="confirm_archive(${bkid})" />`);
            }
            else {
              ret.push(`<img src="{{ url_for('static', filename='icn/inbox-upload.png') }}" title="Unarchive" onclick="confirm_unarchive(${bkid})" />`);
            }
            ret.push(`<img src="{{ url_for('static', filename='icn/minus-button.png') }}" title="Delete" onclick="confirm_delete(${bkid})" />`);

            return ret.join('&nbsp;');
          }
        },

        /* Extra data that is returned in the row for rendering, but not shown. */
        { "name": "BkID", "targets": 5, "data": null, "visible": false },
        { "name": "BkArchived", "targets": 6, "data": null, "visible": false },
        { "name": "WordCount", "targets": 7, "data": null, "visible": false },
        { "name": "UnknownCount", "targets": 8, "data": null, "visible": false },
        { "name": "UnknownPercent", "targets": 9, "data": null, "visible": false },
        { "name": "PageCount", "targets": 10, "data": null, "visible": false },
        { "name": "DistinctCount", "targets": 11, "data": null, "visible": false },
        { "name": "PageNum", "targets": 12, "data": null, "visible": false },
      ],

      // Ajax call
      ajax: {
        url: "/book/datatables/{{ status or 'active' }}",
        type: "POST",
        dataType: "json"
      },

    });

  } // end setup_text_datatable


  $(document).ready(function () {
    setup_text_datatable("{{ initial_search or '' }}");
  });

  function do_action_post(action, bookid) {
    let f = $('#actionposter');
    f.attr('action', `/book/${action}/${bookid}`);
    f.submit();
  }

  function confirm_archive(bookid) {
    do_action_post('archive', bookid);
  }

  function confirm_unarchive(bookid) {
    do_action_post('unarchive', bookid);
  }

  //  function confirm_reparse(bookid) {
  //    if (!confirm(`Reparse the book using parsing rules defined for its language.  This will also reset you to the first page of the book.  Click OK to proceed, or Cancel.`)) {
  //      return;
  //    }
  //    do_action_post('reparse', bookid);
  //  }

  function edit_book(bookid) {
    document.location = `/book/edit/${bookid}`;
  }

  function confirm_delete(bookid) {
    if (!confirm(`Deleting a book.  Click OK to proceed, or Cancel.`)) {
      return;
    }
    do_action_post('delete', bookid);
  }

</script>
