<script lang="ts">
  import QRCode from "qrcode-svg";
  import { Canvg } from "canvg";

  let qrSVG: string;
  let qrText = "";

  $: qrSVG = qrText
    ? new QRCode({
        content: qrText.replace(/</g, "<").replace(/>/g, ">"),
        join: true,
        width: 512,
        height: 512,
        container: 'svg-viewbox',
      }).svg()
    : null;

  let remaining = 2300;

  $: remaining = 2300 - qrText.length;

  function genSvg() {
    return new QRCode({
      content: qrText.replace(/</g, "<").replace(/>/g, ">"),
      join: true,
      width: "512",
      height: "512",
      container: 'svg-viewbox',
    }).svg();
  }

  function genPNG() {
    const canvas = document.getElementById("canv");
    const ctx = canvas.getContext("2d");
    const svg = genSvg();

    const rend = Canvg.fromString(ctx, svg);
    rend.start();

    return canvas.toDataURL("img/png");
  }

  function downloadSVG() {
    const fileName = `${encodeURI(qrText.slice(0, 20))}.svg`;
    const link = document.createElement("a");
    const svgBlob = new Blob([qrSVG], {
      type: "image/svg+xml;charset=utf-8",
    });
    const svgUrl = URL.createObjectURL(svgBlob);
    
    link.download = fileName;
    link.href = svgUrl;
    link.click();
  }

  function downloadPNG() {
    var link = document.createElement("a");

    link.download = `${encodeURI(qrText)}.png`;
    link.href = genPNG();

    link.click();
  }

  function generateQRCode(text: string) {
    qrText = "";
  }
</script>

<textarea
  rows={6}
  maxlength={2300}
  bind:value={qrText}
  placeholder="url or text"
  on:input={() => {
    if (qrText.length > 2300) qrText = qrText.slice(0, 2300);
  }}
/>
<span id="charcount"><span class:red={remaining < 100}>{remaining}</span>/2300</span>

{#if qrSVG}
  <div id="outputs">
    <div id="qrcode" class="qr-code">
        {@html qrSVG}
    </div>
    <div class="buttons">
      <button class="btn btn--secondary" on:click={downloadSVG}>SVG</button>
      <button class="btn btn--secondary" on:click={downloadPNG}>PNG</button>
    </div>
    <canvas id="canv" style="display: none" />
  </div>
{/if}
