"use strict";

(() => {
  const ctx = canvas.getContext("2d");
  const scale = Math.min(canvas.width, canvas.height) / 2;
  ctx.setTransform(
    scale, 0,
    0, -scale,
    canvas.width / 2, canvas.height / 2
  );

  ctx.fillStyle = util.rgb(1, 0, 0);
  ctx.fillRect(-0.5, -0.5, 1, 1);

  perm.addEventListener("click", e => {
    util.getGyroPermission()
    .then((response) => {
      window.addEventListener("deviceorientation", e => {
        const alpha = util.deg2rad(e.alpha);
        const beta = util.deg2rad(e.beta);
        const gamma = util.deg2rad(e.gamma);

        const [screenNormal, phi, theta] = util.toPolarCoordinates(alpha, beta, gamma);
        const theta_ = Math.abs(theta - Math.PI / 2) / Math.PI * 2;
        const phi_ = phi - Math.PI / 2;

        ctx.clearRect(-1, -1, 2, 2);

        const g = theta_;
        ctx.fillStyle = util.rgb(255, g, g);
        ctx.fillRect(-1, -1, 2, 2);

        ctx.strokeStyle = "black";
        ctx.lineWidth = 0.01;
        ctx.beginPath();
        ctx.moveTo(0, 0);
        ctx.lineTo(Math.cos(phi_), Math.sin(phi_));
        ctx.stroke();
      });
    });
  }, { once: true });
})();
