"use strict";

import '@css/pageController.scss';
import Card from "@ventum-digital/ui-components/Card";
import { attachToSailpointBody } from "@ventum-digital/ui-components/Util";
import { div, h2 } from "@ventum-digital/ui-components/BaseElements";
import { getUrlFactory, pluginFetch } from "@ventum-digital/plugin-fetch";


document.addEventListener('DOMContentLoaded', async () => {


  if (!window.location.search.includes("pn=__pluginName__")) {
    return;
  }

  const getUrl = getUrlFactory("__pluginName__");

  let snekContainerId = "snek-container";

  const container = div({},
    Card({
        style: {
          margin: "50px auto 10px"
        }
      },
      h2({
        style: {
          margin: "5px !important",
        }
      }, "Snake Game"),
    ),
    Card({
        id   : snekContainerId,
        style: {
          margin           : "10px auto",
          padding          : "10px",
          display          : "flex",
          "justify-content": "center"
        }
      },
    )
  )

  attachToSailpointBody(container);


  // Get snek color from settings

  let color;

  try {
    color = await pluginFetch(getUrl("getSnekColor"));
  } catch (e) {
    console.error("Error fetching color:", e);
    return;
  }


  ////////////////////////////////////////////////


  let gridSz        = 15, tileCount = 25;
  let head          = {x: Math.floor(tileCount / 2), y: Math.floor(tileCount / 2)};
  let fruit         = {
    x: Math.floor(Math.random() * tileCount),
    y: Math.floor(Math.random() * tileCount)
  };
  let dir           = {x: 0, y: 0};
  let trail         = [];
  let tail          = 15;
  let keyWasPressed = false;



  function snek_sketch(p) {
    function isSnek(point) {
      for (let a = 0; a < trail.length; a++) {
        if (trail[a].x === point.x && trail[a].y === point.y)
          return true;
      }
      return false;
    }

    function isSnekNoHead(point) {
      for (let a = 0; a < trail.length - 1; a++) {
        if (trail[a].x === point.x && trail[a].y === point.y)
          return true;
      }
      return false;
    }

    p.keyPressed = function () {
      if (!keyWasPressed) {
        switch (p.keyCode) {
          case p.UP_ARROW:
            dir = {x: 0, y: -1};
            break;
          case p.DOWN_ARROW:
            dir = {x: 0, y: 1};
            break;
          case p.LEFT_ARROW:
            dir = {x: -1, y: 0};
            break;
          case p.RIGHT_ARROW:
            dir = {x: 1, y: 0};
            break;
        }
        keyWasPressed = true;
      }
    }

    p.setup = function () {
      p.frameRate(15);
      let sz = gridSz * tileCount;
      trail.push(head);
      p.createCanvas(sz, sz);
      p.noStroke();
    }

    p.draw = function () {
      {
        p.background(0);

        head.x += dir.x;
        head.y += dir.y;

        if (head.x < 0)
          head.x = tileCount - 1;
        if (head.x >= tileCount)
          head.x = 0;
        if (head.y < 0)
          head.y = tileCount - 1;
        if (head.y >= tileCount)
          head.y = 0;

        trail.push({x: head.x, y: head.y});

        if (isSnekNoHead(head))
          tail = 5;

        while (trail.length > tail) {
          trail.shift();
        }

        if (head.x === fruit.x && head.y === fruit.y) {
          tail++;
          do {
            fruit = {
              x: Math.floor(Math.random() * tileCount),
              y: Math.floor(Math.random() * tileCount)
            };
          } while (isSnek(fruit));
        }

        for (let a = trail.length - 1; a >= 0; a--) {
          p.fill(color.r, color.g, color.b);
          p.rect(gridSz * trail[a].x, gridSz * trail[a].y, gridSz, gridSz);
        }

        p.fill(200, 20, 0);
        p.rect(gridSz * fruit.x, gridSz * fruit.y, gridSz, gridSz);


        if (keyWasPressed)
          keyWasPressed = false;
      }

    }
  }


  // Create a new p5 instance with the snek sketch
  // @ts-ignore - loaded in page.xthml
  new p5(snek_sketch, snekContainerId)

});