import {
  Component,
  createEffect,
  createResource,
  JSX,
  splitProps,
} from "solid-js";
import qrcode from "qrcode";

const QrCode: Component<
  {
    margin?: number;
    value: string;
    errorCorrectionLevel?: string;
  } & JSX.HTMLAttributes<HTMLDivElement>
> = (p) => {
  const [props, rest] = splitProps(p, [
    "margin",
    "value",
    "errorCorrectionLevel",
  ]);

  let ref: HTMLDivElement = undefined!;

  const [svg] = createResource(
    () => props.value,
    (value) => {
      return qrcode.toString(value, {
        type: "svg",
        margin: props.margin,
        errorCorrectionLevel: props.errorCorrectionLevel,
      });
    }
  );

  createEffect(() => {
    const html = svg();
    requestAnimationFrame(function () {
      ref.innerHTML = html;
    });
  });

  return <div ref={ref} {...rest}></div>;
};

export default QrCode;
