<script>/*
Include this template to show control buttons (back and print) at the bottom of the page

Add class `print-repeated` to the element (do not add it to <body>) you want to repeat while printing.

This file should be self-contained. Do not import or use Bootstrap here, it may mess with templates that use this component
*/</script>


<script>
  const localPrint = (/** Number */ copies, /** String */ targetClass = 'print-repeated') => {
    const toRepeat = document.getElementsByClassName(targetClass)?.[0]

    if (copies === 1 || !toRepeat) {
      if (copies !== 1) {
        console.warn("Requested more than 1 copy but the element to repeat was not found")
      }

      window.print()
      return
    }

    let repeatedElements = []

    for (let i = 0; i < copies-1; i++) {
      repeatedElements.push(toRepeat.cloneNode(true))
      toRepeat.after(repeatedElements.at(-1))
    }

    window.print()

    // setTimeout to place this at the end of the event loop, after we print
    setTimeout(() => { repeatedElements.map(element => element.remove()) }, 1)
  }

  async function remotePrint(/** Number */ copies) {
    const response = await fetch(`{{ url_prefix }}/print/send`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        copies,
        url: window.location.href,
        filename: `{{ print_name or '' }}`,
      }),
    })

    let json
    try {
      json = await response.clone().json()
    } catch {
      alert(`Error ${response.status}: ${await response.text()}`)
      return
    }

    // TODO: This is not translated
    if (!response.ok) {
      alert(`Error ${response.status}: ${json.error}`)
    } else {
      // don't bother the user with the success message
      // alert(json.message)
    }
  }

  async function doPrint(/** Number */ copies) {
    if ({{ 1 * setup.enable_auto_print }}) {
      await remotePrint(copies)
    } else {
      localPrint(copies)
    }
  }

  // Change the title for printouts when saving PDF
  (() => {
    const originalTitle = document.title;
    const newTitle = `{{ print_name or '' }}`

    if (newTitle.length === 0) {
      console.warn("Template variable `print_name` missing")
      return
    }

    window.addEventListener('afterprint', () => { document.title = originalTitle });
    window.addEventListener('beforeprint', () => { document.title = newTitle });
  })();
</script>


<style>
    :root {
        --control-buttons-size: 100px;
    }

    @media print {
        #control-buttons {
            display: none;
        }
    }

    #control-buttons {
        padding-top: calc(20px + var(--control-buttons-size));
    }

    #control-buttons > div {
        width: calc(100% - 20px);
        position: fixed;
        display: flex;
        justify-content: space-between;
        top: calc(100% - var(--control-buttons-size) - 10px);
        left: 10px;
    }

    #control-buttons img {
        width: var(--control-buttons-size);
        height: var(--control-buttons-size);
        cursor: pointer;
    }

    .print-repeated {
        break-after: page;
    }

    .repeated-print-button {
        line-height: 1;
        font-size: calc(var(--control-buttons-size) / 3);
        cursor: pointer;
    }
</style>


<div id="control-buttons">
    <div>
        <img
          src="{{ url_prefix }}/static/back-arrow.png"
          onclick="window.history.back()"
          alt="{{ tran('{go_back}') }}"
          title="{{ tran('{go_back}') }}"
        />

        <div style="display: flex;">
            <img
              src="{{ url_prefix }}/static/print-button.svg"
              onclick="doPrint(1)"
              alt="{{ tran('{print}') }}"
              title="{{ tran('{print}') }}"
            />
            <div class="pointer" style="display: grid;">
                <b class="repeated-print-button" title="{{ tran('{print}') }} x2" onclick="doPrint(2)">x2</b>
                <b class="repeated-print-button" title="{{ tran('{print}') }} x3" onclick="doPrint(3)">x3</b>
                <b class="repeated-print-button" title="{{ tran('{print}') }} x4" onclick="doPrint(4)">x4</b>
            </div>
        </div>
    </div>
</div>
