{% macro filter(name, value) %}{{ url_for('bookmark.index_view', **{'flt0_'+name: value}) }}{% endmacro %}

{% macro bookmarklet() -%}
  {% with url = url_for('bookmarklet', _external=True) -%}
    {% include 'bukuserver/bookmarklet.url' %}
  {%- endwith %}
{%- endmacro %}

{% macro script(filename) %}
  <script src="{{ url_for('static', filename='bukuserver/js/'+filename) }}"></script>
{% endmacro %}

{% macro close_if_popup() %}
  <script>opener && (opener !== window) && close()</script>
{% endmacro %}

{% macro limit_navigation_if_popup() %}
  <style>
    .popup .navbar-brand {pointer-events: none}
    .popup :is(#admin-navbar-collapse, .navbar-toggle) {display: none !important}
    .popup .nav-tabs :is(:first-child, :nth-child(2):not(.active)) > * {display: none}
  </style>
  <script>opener && (opener !== window) && document.body.classList.add('popup')</script>
{% endmacro %}

{% macro fetch_checkbox(checked=True) %}
  <script>
    $('.admin-form [name=fetch]').remove();
    $('.admin-form').append(
      $(`<label class="form-group" style="display: block"><span class="col-md-2 text-right">{{ _gettext('Fetch') }}</span>`
        +`<span class="col-md-10"><input type="checkbox" name="fetch"{% if checked %} checked{% endif %}></span></label>`))
  </script>
{% endmacro %}

{% macro details_formatting(prefix='') %}
  <script>{
    const TARGET = {{ (' target="_blank"' if config.get('BUKUSERVER_OPEN_IN_NEW_TAB', False) else '') | tojson }};
    $(`{{prefix}} td:nth-child(2)`).html((_, s) => s.trim().replaceAll('\n', '<br/>'));
    {% if session.pop('netloc', None) %}
    $(`{{prefix}} td:contains({{ _gettext('Url') | tojson }}) + td`).html((_, s) => `<a href="${s.replaceAll('"', '&quot;')}"${TARGET}>${s}</a>`);
    {% endif %}
  }</script>
{% endmacro %}

{% macro link_saved() %}
  {% set backlink = request.args.get('url', request.full_path) %}
  {% set saved = session.pop('saved', None) %}
  {% if saved %}
  <script>{
    const SUCCESS = [{{ _gettext('Record was successfully created.') | tojson }},
                     {{ _gettext('Record was successfully saved.') | tojson }}];
    $(`.alert-success`).filter((idx, e) => SUCCESS.some(s => e.innerText.includes(s))).html((_, s) =>
      s.replace(/(<\/button>)([^]*)$/, `$1<a href="{{ url_for('.details_view', id=saved, url=backlink) }}">$2</a>`));
  }</script>
  {% endif %}
{% endmacro %}
