import { StickyNote, Image } from "@mirohq/websdk-types";
import { getStickiesToChopInTree } from "./todo-tree-helper";

export const init = async () => {
  miro.board.ui.on('icon:click', async () => {
    await miro.board.ui.openPanel({ url: 'app.html' });
  });

  await miro.board.ui.on('custom:chop-todo-tree', handleChoppingAction);
  await miro.board.experimental.action.register(
    {
      "event": "chop-todo-tree",
      "ui": {
        "label": {
          "en": "Chop TODO tree",
        },
        "icon": "scissors",
        "description": "Chop down TODO tree staring here",
      },
      "scope": "local",
      "predicate": {
        "type": "sticky_note"
      },
      "contexts": {
        "item": {}
      }
    }
  );
}

interface AxeAnimationArgs {
  axe: Image,
  stickyNote: StickyNote,
  onChopped: () => void
}

const playAxeAnimation = async ({axe, stickyNote, onChopped}: AxeAnimationArgs) => {
  const originalX = axe.x;
  const originalY = axe.y;
  
  await miro.board.bringToFront(axe);
  axe.x = stickyNote.x;
  axe.y = stickyNote.y;
  await axe.sync();

  for (let i = 0; i < 3; i++) {
    axe.rotation = 90;
    await axe.sync();
    await new Promise(resolve => setTimeout(resolve, 300));

    axe.rotation = 0;
    await axe.sync();
    await new Promise(resolve => setTimeout(resolve, 300));
  }

  onChopped();
  
  axe.x = originalX;
  axe.y = originalY;
  await axe.sync();
}

const postInfoNotification = async (message: string) =>  
  await miro.board.notifications.showInfo(message);

const handleChoppingAction = async ({items}: {items:StickyNote[]}) => {
  const axe = await findExistingAxe();

  if (items.length === 0) {
    postInfoNotification("Couldn't find anything to chop 🤔")
    return;
  }

  if (!axe) {
    postInfoNotification('No axe found. Create it first.');
    return;
  }

  const target = items[0];
  playAxeAnimation({
    axe,
    stickyNote: target,
    onChopped: () => removeTree(target)
  });
};

const removeTree = async (root: StickyNote) => {
  const stickiesToRemove = await getStickiesToChopInTree(root, ["light_green", "red"]);
  
  for (const item of stickiesToRemove) {
    await miro.board.remove(item);
  }
};

export const findExistingAxe = async () => {
  const items = await miro.board.get({ type: 'image' });
  const axe = items.find(item => item.title === 'todo-tree-axe');
  return axe;
};

init();
