{% extends "app_home/base.html" %}
{% load static %}
{% load i18n %}

{% block navbar_app %}
{% include 'app_home/_sidebar.html' %}
{% endblock %}




{% block title %}
<h2><i class="fa {{ schema.icon }}"></i> &nbsp; {{ schema.displayname }}</h2>
  <small class="text-muted">{{ instances_count }} / {{ paginator.count }} {% translate "objects" %}</small>
<hr>
{% endblock %}


{% block content %}

<div class="d-flex">


  <div class="mt-2 me-2"> <!-- ACTION -->
    <div class="dropdown">

      <button class="btn btn-outline-dark dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false">
        <i class="fa fa-lg fa-plus me-2"></i>{% translate 'Action' %}
      </button>

      <ul class="dropdown-menu">

        {% if ui_new %}
        <li>
          <a class="dropdown-item" href="{% url 'app_data:instance_new' schema.classname %}">
            {% translate 'New' %}
          </a>
        </li>
        {% endif %}

        {% if ui_export %}
        <li>
          <a class="dropdown-item" data-bs-toggle="modal" data-bs-target="#ExportModal">
            {% translate "Export" %}
          </a>
        </li>
        {% endif %}


        {% if ui_texteditor %}
        <li>
          <a class="dropdown-item" href="{% url 'app_data:texteditor' schema.classname %}">
            {% translate "Schema" %}</a>
        </li>
        {% endif %}

      </ul>
    </div>
  </div>


  <div class="p-2">   <!-- DATAVIEW -->
    <button class="btn btn-outline-dark dropdown-toggle px-4 me-2" type="button" data-bs-toggle="dropdown">
      <i class="fa fa-lg fa-eye me-2"></i>{{ dataview.displayname }}
    </button>
    <div class="dropdown-menu">
      {% if dataview.default %}
      <a class="dropdown-item" href="?dv={{ dataview.default }}">{% translate 'Default View' %}</a>
      {% endif %}
      {% for name,value in dataview.selector.items %}
          <a class="dropdown-item" href="?dv={{ name }}">{{ value }}</a>
      {% endfor %}
    </div>
</div>


  <div class="flex-grow-1 p-2"> <!-- SEARCH -->
    <form class="cv-search-form" action="" method="post"> {% csrf_token %}
        <button class="btn btn-success me-2" type="submit" id="search">
          <i class="fa fa-lg fa-search"></i>
        </button>
        <input type="text" class="form-control" size="120" placeholder="{% translate 'search...' %}"
        name="query" value="{{ query }}">
    </form>
  </div>



  <div class="d-flex justify-content-center"> <!-- PAGINATOR  -->
    <div class="btn-group">

      {% if paginator.page_last > 1 %}
      <div class="mx-3 pt-2"> <!-- PAGINATOR :  PREV | FIRST (bool)|| CURRENT or page... || LAST | NEXT -->
        <ul class="pagination">

          <!-- PREV -->
          <li class="page-item">
            <a class="page-link" href="?page={{ paginator.page_prev }}&size={{ paginator.size }}">
              &laquo;
            </a>
          </li>

          <!-- FIRST -->
          {% if paginator.page_first %}
          <li class="page-item">
            <a class="page-link active" href="?page=1&size={{ paginator.size }}">
              1
            </a>
          </li>
          {% else %}
          <li class="page-item">
            <a class="page-link" href="?page=1&size={{ paginator.size }}">
              1
            </a>
          </li>
          {% endif %}

        &nbsp;&nbsp;&nbsp;  <!-- CURRENT -->

          {% if paginator.page_current %}
          <li class="page-item">
            <a class="page-link active" href="?page={{ paginator.page }}&size={{ paginator.size }}">
            {{ paginator.page }}
            </a>
          </li>
          {% else %}
          <li class="page-item">
            <a class="page-link disabled">
              ...
            </a>
          </li>
          {% endif %}

        &nbsp;&nbsp;&nbsp;

          <!-- LAST -->
          {% if paginator.page_last_active %}
          <li class="page-item">
            <a class="page-link active" href="?page={{ paginator.page_last }}&size={{ paginator.size }}">
              {{ paginator.page_last }}
            </a>
          </li>
          {% else %}
          <li class="page-item">
            <a class="page-link" href="?page={{ paginator.page_last }}&size={{ paginator.size }}">
              {{ paginator.page_last }}
            </a>
          </li>
          {% endif %}

          <!-- NEXT -->
          <li class="page-item">
            <a class="page-link" href="?page={{ paginator.page_next }}&size={{ paginator.size }}">
              &raquo;
            </a>
          </li>

        </ul>
      </div>

      <!-- SIZE -->
      <div class="mx-3 pt-2">
        <a class="btn btn-outline-primary dropdown-toggle me-4" href="#" role="button" data-bs-toggle="dropdown">
          {{ paginator.size }} {% translate 'per page' %}
        </a>
        <div class="dropdown-menu">
          {% for s in paginator.size_list %}
          <a class="dropdown-item" href="{% url 'app_data:instance_list' schema.classname %}?size={{s}}">
            {{s}}
          </a>
          {% endfor %}
        </div>
      </div>

      {% endif %}

    </div>
  </div>

</div>


<table class="table table-striped table-hover table-sm table-bordered">
<thead class="thead-dark">
    <tr>
    <th></th>
    {% for i in dataview.columns %}
        {% if i == 'keyname' %}<th>{{ schema.keyname_label|default:'Keyname' }}</th>
        {% elif i == 'displayname' %}<th>{{ schema.displayname_label|default:'Name' }}</th>
        {% elif i == 'last_update' %}<th>{% translate 'Last Update' %}</th>
        {% else %}<th class="text-center">{{ i }}</th>{% endif %}
    {% endfor %}
    </tr>
</thead>

<tbody class="small">{% for instance in instances %}
  <tr>
    <td class="cv-burger-cell">
      <button class="cv-burger-btn btn btn-sm"
        data-iid="{{ instance.id }}"
        data-keyname="{{ instance.keyname }}"
        data-classname="{{ schema.classname }}"
        data-is-enabled="{{ instance.is_enabled|yesno:'1,0' }}"
        data-ui-edit="{{ instance.ui_edit|yesno:'1,0' }}"
        data-ui-delete="{{ instance.ui_delete|yesno:'1,0' }}"
        data-ui-ed="{{ instance.ui_enable_disable|yesno:'1,0' }}"
        data-ui-code="{{ ui_texteditor|yesno:'1,0' }}"
      ><i class="fa fa-ellipsis-v"></i></button>
    </td>
    {% for item in instance.datapoints %} <!-- cell -->
        {% if item.fieldname %} <!-- it's a datapoint -->
           <td>{% include 'app_data/fields/_datapoint_nolink.html' %}</td>
        {% else %}  <!-- keyname/displayname non-field cell -->
            <td>
              <a href="{% url 'app_data:instance_detail' instance.id %}">
            {% if instance.is_enabled %}{{ item|default:'' }}{% else %}<del>{{ item|default:'' }}</del>{% endif %}
              </a>
            </td>
        {% endif %}
    {% endfor %}
  </tr>
{% endfor %}
</tbody>
</table>


<!-- BURGER: shared row action dropdown -->
<div id="cv-row-menu" class="cv-row-menu dropdown-menu shadow"
  data-tpl-detail="{% url 'app_data:instance_detail' 0 %}"
  data-tpl-edit="{% url 'app_data:instance_edit' 0 %}"
  data-tpl-enable="{% url 'app_data:instance_enable' 0 %}"
  data-tpl-disable="{% url 'app_data:instance_disable' 0 %}"
  data-tpl-delete="{% url 'app_data:instance_delete' 0 %}"
  data-tpl-code="{% url 'app_data:texteditor' 0 %}">
  <a id="cv-menu-detail"  class="dropdown-item" href="#">{% translate "Detail" %}</a>
  <div class="dropdown-divider"></div>
  <a id="cv-menu-edit"    class="dropdown-item" href="#">{% translate "Edit" %}</a>
  <a id="cv-menu-enable"  class="dropdown-item" href="#">{% translate "Enable" %}</a>
  <a id="cv-menu-disable" class="dropdown-item" href="#">{% translate "Disable" %}</a>
  <a id="cv-menu-delete"  class="dropdown-item cv-menu-danger" href="#">{% translate "Delete" %}</a>
  <div class="dropdown-divider"></div>
  <a id="cv-menu-print"   class="dropdown-item" href="#" target="_blank">{% translate "Print" %}</a>
  <a id="cv-menu-code"    class="dropdown-item" href="#">{% translate "Code" %}</a>
</div>


<!-- BURGER: confirm Enable modal -->
<div class="modal fade" id="cv-modal-enable" data-bs-backdrop="static" tabindex="-1">
  <div class="modal-dialog"><div class="modal-content">
    <div class="modal-header">
      <h5 class="modal-title">{% translate "Confirm enable?" %}</h5>
      <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
    </div>
    <div class="modal-body"><p id="cv-modal-enable-label" class="fw-bold"></p></div>
    <div class="modal-footer">
      <form id="cv-modal-enable-form" method="post"
            data-tpl="{% url 'app_data:instance_enable' 0 %}">
        {% csrf_token %}
        <button class="btn btn-success">{% translate "Enable" %}</button>
        <a role="button" class="btn btn-outline-dark" data-bs-dismiss="modal">{% translate "Cancel" %}</a>
      </form>
    </div>
  </div></div>
</div>


<!-- BURGER: confirm Disable modal -->
<div class="modal fade" id="cv-modal-disable" data-bs-backdrop="static" tabindex="-1">
  <div class="modal-dialog"><div class="modal-content">
    <div class="modal-header">
      <h5 class="modal-title">{% translate "Confirm disable?" %}</h5>
      <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
    </div>
    <div class="modal-body"><p id="cv-modal-disable-label" class="fw-bold"></p></div>
    <div class="modal-footer">
      <form id="cv-modal-disable-form" method="post"
            data-tpl="{% url 'app_data:instance_disable' 0 %}">
        {% csrf_token %}
        <button class="btn btn-warning">{% translate "Disable" %}</button>
        <a role="button" class="btn btn-outline-dark" data-bs-dismiss="modal">{% translate "Cancel" %}</a>
      </form>
    </div>
  </div></div>
</div>


<!-- BURGER: confirm Delete modal -->
<div class="modal fade" id="cv-modal-delete" data-bs-backdrop="static" tabindex="-1">
  <div class="modal-dialog"><div class="modal-content">
    <div class="modal-header">
      <h5 class="modal-title">{% translate "Confirm delete?" %}</h5>
      <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
    </div>
    <div class="modal-body"><p id="cv-modal-delete-label" class="fw-bold"></p></div>
    <div class="modal-footer">
      <form id="cv-modal-delete-form" method="post"
            data-tpl="{% url 'app_data:instance_delete' 0 %}">
        {% csrf_token %}
        <button class="btn btn-danger">{% translate "Delete" %}</button>
        <a role="button" class="btn btn-outline-dark" data-bs-dismiss="modal">{% translate "Cancel" %}</a>
      </form>
    </div>
  </div></div>
</div>


<!-- EXPORT Modal -->
<div class="modal fade" id="ExportModal" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">

      <div class="modal-header">
        <h1 class="modal-title fs-5" id="staticBackdropLabel">{% translate "Configure export" %}</h1>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <form action="{% url 'app_data:data_export' %}" method="post">{% csrf_token %}
        <div class="modal-body">

          <h4><i class="fa {{ schema.icon }}"></i> &nbsp; {{ schema.displayname }} ({{ schema.classname }})</h4>
          <br>
          <input type="hidden" name="classname" value="{{ schema.classname }}">
          <input type="hidden" name="query" value="{{ query }}">

          <p>{% translate 'Search query' %} : {{ query|default:'n/a'}}</p>

          <br>
          <h5>{% translate 'Vue' %}</h5>
          <div class="form-check">
            <input class="form-check-input" type="radio" name="dv" value="{{ dataview.keyname }}" checked>
            <label class="form-check-label" for="dataview">
              {% translate 'Current View' %} : {{ dataview.displayname }}
            </label>
          </div>
          <div class="form-check">
            <input class="form-check-input" type="radio" name="dv" value="___ALL___">
            <label class="form-check-label" for="allcols">
              {% translate 'All columns' %}
            </label>
          </div>

          <br>
          <h5>{% translate 'Page' %}</h5>
          <div class="form-check">
            <input class="form-check-input" type="radio" name="page" value="thispage" checked>
            <label class="form-check-label" for="thispage">
              {% translate 'This page' %} - {{ paginator.page }} / {{ paginator.page_last }}
             </label>
          </div>
          <div class="form-check">
            <input class="form-check-input" type="radio" name="page" value="allpages">
            <label class="form-check-label" for="allpages">{% translate 'All pages' %}</label>
          </div>

          <br>
          <h5>{% translate 'Format' %}</h5>
          <div class="form-check">
            <input class="form-check-input" type="radio" name="format" value="yaml" checked>
            <label class="form-check-label" for="yaml">{% translate 'YAML' %}</label>
          </div>
          <div class="form-check">
            <input class="form-check-input" type="radio" name="format" value="json">
            <label class="form-check-label" for="json">{% translate 'JSON' %}</label>
          </div>
          <div class="form-check">
            <input class="form-check-input" type="radio" name="format" value="csv">
            <label class="form-check-label" for="csv">{% translate 'CSV' %}</label>
          </div>

          <br>
          <h5>{% translate 'Options' %} (YAML / JSON)</h5>
          <div class="mb-2">
            <label class="form-label" for="refs">{% translate 'Inline refs' %}</label>
            <input type="text" class="form-control form-control-sm" name="refs" id="refs" placeholder="e.g. _user,server  (* = all)">
            <div class="form-text">{% translate 'Comma-separated schema names to inline, or * for all' %}</div>
          </div>
          <div class="mb-2">
            <label class="form-label" for="rev">{% translate 'Revisions' %}</label>
            <input type="number" class="form-control form-control-sm" name="rev" id="rev" min="1" placeholder="{% translate 'number of revisions' %}">
          </div>

        </div>
        <div class="modal-footer">
          <button role="button" class="btn btn-danger">{% translate "Export" %}</button>
          <a role="button" class="btn btn-outline-dark" data-bs-dismiss="modal">{% translate "Cancel" %}</a>
        </div>
      </form>
    </div>
  </div>
</div>


<script>
document.addEventListener('DOMContentLoaded', function () {

    const menu = document.getElementById('cv-row-menu');
    let activeBtn = null;

    function resolveUrl(action, iid) {
        return menu.dataset['tpl' + action.charAt(0).toUpperCase() + action.slice(1)]
                   .replace('/0/', '/' + iid + '/');
    }

    function closeMenu() { menu.style.display = 'none'; }

    function tog(id, hidden) {
        document.getElementById(id).classList.toggle('d-none', hidden);
    }

    document.querySelectorAll('.cv-burger-btn').forEach(function (btn) {
        btn.addEventListener('click', function (e) {
            e.stopPropagation();
            activeBtn = btn;
            const d = btn.dataset;
            const iid = d.iid;
            const enabled = d.isEnabled === '1';

            document.getElementById('cv-menu-detail').href = resolveUrl('detail', iid);
            document.getElementById('cv-menu-edit').href   = resolveUrl('edit',   iid);
            document.getElementById('cv-menu-print').href  = resolveUrl('detail', iid) + '?print=1';
            document.getElementById('cv-menu-code').href   = resolveUrl('code',   iid);

            tog('cv-menu-edit',    d.uiEdit   !== '1');
            tog('cv-menu-delete',  d.uiDelete !== '1');
            tog('cv-menu-code',    d.uiCode   !== '1');
            tog('cv-menu-enable',  d.uiEd !== '1' || enabled);
            tog('cv-menu-disable', d.uiEd !== '1' || !enabled);

            const rect = btn.getBoundingClientRect();
            menu.style.left    = rect.left + 'px';
            menu.style.top     = rect.bottom + 'px';
            menu.style.display = 'block';
        });
    });

    document.addEventListener('click', closeMenu);

    ['enable', 'disable', 'delete'].forEach(function (action) {
        document.getElementById('cv-menu-' + action).addEventListener('click', function (e) {
            e.preventDefault();
            closeMenu();
            const d = activeBtn.dataset;
            const form = document.getElementById('cv-modal-' + action + '-form');
            form.action = form.dataset.tpl.replace('/0/', '/' + d.iid + '/');
            document.getElementById('cv-modal-' + action + '-label').textContent =
                d.classname + ' : ' + d.keyname;
            bootstrap.Modal.getOrCreateInstance(
                document.getElementById('cv-modal-' + action)
            ).show();
        });
    });

});
</script>


{% endblock %}
