{% set admin_kwargs = handler.kwargs.get('admin_kwargs', '') or {} %}
<!--IDE HTML-->
{% from nlg.webapp import read_current_config, get_user_dir, is_user_authenticated %}
{% set dsid = read_current_config(handler).get('dsid') %}

<div class="container-fluid pt-4">
  <div class="form-inline">
    <div class="form-row align-items-center">
      <div class="col-auto">
        <label for="narrative-name-editor">Narrative Title</label>
      </div>
      <div class="col-auto">
        <input class="form-control" id="narrative-name-editor" placeholder="Name the Narrative">
      </div>
      <div class="col-auto">
        <button type="button" class="btn btn-primary round" data-toggle="modal"
        data-target=".grmform-modal">
          Add Data <i class="fa fa-plus"></i>
        </button>
      </div>
    </div>
  </div>

  <!-- GRMFORM HTML -->
  <div class="modal fade grmform-modal" tabindex="-1" role="dialog" aria-labelledby="grmformModalLabel" aria-hidden="true">
    {% from nlg.webapp import get_dataset_files, get_narrative_config_files %}
    {% set NLG_DATASETS = get_dataset_files(handler) %}
    {% set NLG_NARRATIVES = get_narrative_config_files(handler) %}
    {% import os.path as op %}
    <div class="modal-dialog modal-lg">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title">Select Data & Narrative</h5>
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
      <div class="modal-body">
        <form id="nlg-init-form" action="{{ nlg_base }}/initform?next={{ nlg_base }}"
        method="POST" enctype="multipart/form-data">
          <div class="row">
            <div class="col">
              <select name="dataset" id="dataset-select" class="form-control" form="nlg-init-form">
                {% for filename in NLG_DATASETS %}
                <option value="{{ filename }}">{{ op.basename(filename) }}</option>
                {% end %}
                <option value="" hidden selected>Select Dataset</option>
              </select>
            </div>
            <div class="col">
              <select name="narrative" id="narrative-select" class="form-control" form="nlg-init-form">
                {% for filename in NLG_NARRATIVES %}
                <option value="{{ filename }}">{{ op.basename(filename) }}</option>
                {% end %}
                <option value="" selected hidden>Select Narrative</option>
              </select>
            </div>
          </div>
          <div class="divider">Or Upload New</div>
          <div class="row">
            <input type="hidden" name="_xsrf" value="{{ handler.xsrf_token }}">
            <div class="col">
              <label for="fileupload">Dataset:</label>
              <input id="fileupload" name="data-file" type="file" class="form-control-file">
            </div>
            <div class="col">
              <label for="narrativeupload">Config:</label>
              <input id="narrativeupload" name="config-file" type="file"
              class="form-control-file">
            </div>
          </div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="submit" form="nlg-init-form" class="btn btn-primary">Submit</button>
      </div>
    </div>
  </div>
  </div> <!--GRMFORM HTML END-->

  <!-- <div class="container-fluid">-->
  <div class="row">
    <div class="col">
      <script id="template-preview" type="text/html">
        <div>
          <% for (let i=0; i < templates.length; i++) { %>
            <div class="pb-1">
              <button id="rm-btn-<%= i %>" title="Remove" type="button" class="btn btn-danger btn-sm">
                <i class="fa fa-trash"></i>
              </button>
              <button id="settings-btn-<%= i %>" title="Settings" type="button" class="btn btn-primary btn-sm">
                <i class="fa fa-wrench"></i>
              </button>
              <%= templates[i].previewHTML %>
            </div>
          <% } %>
        </div>
      </script>
    </div>
    <div class="col-sm-3">
      <button id="save-config-btn" type="button" title="Save Config"
      class="btn btn-primary">
      Save Config
      <i class="fa fa-save"></i>
      </button>
      <button id="share-narrative-btn" type="button" title="Embed Narrative"
      class="btn btn-primary">
          Embed
          <i class="fa fa-code"></i>
      </button>
      <div class="alert alert-success alert-dismissable collapse" role="alert">
        <strong>Saved!</strong>
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
      </div>
    </div>
  </div>


  <div class="divider"></div>
  <form id="myform" enctype="multipart/form-data">
      <div class="form-group">
          <label for="textbox">Type Something:</label>
          <textarea class="form-control" id="textbox" name="textbox"
          class="text-monospace"></textarea>
      </div>
      <p>
          <button id="inspect" type="button" title="Add to Template"
              class="btn btn-primary">Add to Narrative
              <i class="fa fa-plus-square"></i>
          </button>
      </p>
  </form>
  <div class="divider"></div>
  {% if dsid %}
  {% from os.path import basename %}
  {% set user_dir = basename(get_user_dir(handler)) %}
  <div class="formhandler" data-src="{{ nlg_base }}/preview/{{ user_dir }}/{{ dsid }}"></div>
  {% end %}

  <div class="modal fade" id="template-settings" role="dialog">
    <div class="modal-dialog modal-lg">
      <div class="modal-content">
        <div class="modal-header"><h6>Template Settings</h6></div>
          <div id="tmpllist" class="modal-body">
            <div>
            <div class="card shadow mb-3">
              <div class="card-body">
                <h4 class="card-title">Template Preview</h4>
                <p class="card-text" id="tmpl-setting-preview"></p>
              </div>
            </div>
            <div class="form-group row">
              <label class="col-sm-4 col-form-label"
              for="tmpl-name-editor">Template Name</label>
              <div class="col-sm-4">
                <input class="form-control"
                id="tmpl-name-editor" placeholder="Name the template">
              </div>
              <div class="col-sm-4">
                <button id="tmpl-name-btn" type="button" class="btn btn-primary success">
                    <i class="fa fa-check"></i>
                </button>
              </div>
            </div>
            <div class="form-group row">
              <label class="col-sm-4 col-form-label"
              for="condition-editor">Condition</label>
              <div class="col-sm-4">
                <input class="form-control"
                id="condition-editor" placeholder="Add condition">
              </div>
              <div class="col-sm-4">
                <button id="condition-btn" type="button" class="btn btn-primary success">
                    <i class="fa fa-check"></i>
                </button>
              </div>
            </div>
            <div class="form-group">
              <textarea class="form-control align-center text-monospace"
              id="edit-template" name="templateditor" rows="10"></textarea>
            </div>
            <table class="table table-striped table-sm">
              <thead>
                  <tr>
                      <th scope="col">Token</th>
                      <th scope="col">Search Results</th>
                      <th scope="col">Grammar</th>
                  </tr>
              </thead>
              <tbody id="table-body">
                <script type="text/html" id="tmplsettings">
                  <% for (let [token, tkobj] of Object.entries(tokenmap)) { %>
                  <tr>
                    <th scope="row" class="align-middle"><%= token %></th>
                    <% if (tkobj.tokenlist.length > 1) { %>
                      <td>
                        <% let tkselector = token.replace(/\s/g, "_") %>
                        <% let ddid = `srdd-${currentEditIndex}-${tkselector}` %>
                        <div class="text-monospace">
                          <select class="selectpicker" id="<%= ddid %>">
                          <option selected>
                              <%= tkobj.enabledTemplate.tmpl %>
                          </option>
                          <% for (let i = 0; i < tkobj.tokenlist.length; i++) { %>
                            <% let tmpl = tkobj.tokenlist[i] %>
                            <% if (!(tmpl.enabled)) { %>
                              <div class="text-monospace">
                                <option><%= tmpl.tmpl %></option>
                              </div>
                            <% } %>
                          <% } %>
                          </select>
                        </div>
                      </td>
                    <% } else { %>
                      <td class="align-middle" style="font-family:monospace"><%= tkobj.tokenlist[0].tmpl %></td>
                    <% } %>
                    <td class="align-middle">
                      <% var tkselector = tkobj.text.replace(/\s/g, '_') %>
                      <select id="gramopt-select-<%= currentEditIndex %>-<%= tkselector %>" class="select-multiple" multiple="multiple">
                        <% var appliedInfls = findAppliedInflections(tkobj) %>
                        <% var selected %>
                        <% for (let fe_name of Object.keys(grammarOptions)) { %>
                          <% selected = '' %>
                          <% if (appliedInfls.has(fe_name)) { %>
                            <% selected = 'selected' %>
                          <% } %>
                        <option <%= selected %>><%= fe_name %></option>`
                        <% } %>
                      </select>
                    </td>
                  </tr>
                  <% } %>
                </script>
              </tbody>
            </table>
            <div id="srdd"></div>
            <button id="check-template" title="Run template"
            type="button" class="btn btn-primary btn-sm">
                Run Template <i class="fa fa-play"></i>
            </button>
            <button id="save-template" title="Save Template"
            type="button" class="btn btn-primary btn-sm" disabled>
                Save Template <i class="fa fa-save"></i>
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- traceback modal-->
  <div id="tb-modal" class="modal fade bd-example-modal-lg" tabindex="-1"
  role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title">Traceback</h5>
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
        <div class="modal-body" id="traceback">
        </div>
      </div>
    </div>
  </div>
</div>

<!-- Include JS dependencies -->
<script src="{{ nlg_base }}/ui/bootstrap-select/dist/js/bootstrap-select.min.js"></script>
<script src="{{ nlg_base }}/nlg.js"></script>
<script>
  $.fn.selectpicker.Constructor.BootstrapVersion = '4'
  var nlg_base = "{{ nlg_base }}"
  var df = null;
  var args = null;
  var templates = [];
  var currentEventHandlers = {};
  var currentEditIndex = null;
  var currentSpanId = null;
  var grammarOptions = []
  var narrative_name = "";
  var dataset_name = "";

  $(document).ready(setInitialConfig)

  $('.formhandler').on('load', renderPreview)
  $('.formhandler').formhandler()

  $(document)
  .on('click', '#save-config-btn', saveConfig)
  .on('click', '#inspect', addToNarrative)
  .on('click', '#check-template', checkTemplate)
  .on("click", "#save-template", saveTemplate)
  .on('focus', "#edit-template", (e) => {$('#save-template').attr('disabled', false)})
  .on('click', "#condition-btn", addCondition)
  .on('click', "#share-narrative-btn", shareNarrative)
  .on('click', "#tmpl-name-btn", addName)

  $("#textbox").attr('cols', 119)
  $("#edit-template").attr('cols', 69).attr('rows', 10)
  $.getJSON(`{{ nlg_base }}/get-gramopts`).done(
    (resp) => { grammarOptions = resp }
  )
</script>
