import { nextTick, watch, reactive, ref, computed, onMounted, onUnmounted } from "vue";
import { getQuery, homeAction } from "../kirby.js";
import { handleActive, ArrowVerticalKeyHandler, ArrowHorizontalKeyHandler, NumberKeyHandler } from "../handlers.js";
import { overlayAndGet, powerStateMachine, popLastElem } from "../componentPromise.js";

const html = (v) => { return v[0] };


////////////////////////////////////////////////////////////////////////////////
// Components
////////////////////////////////////////////////////////////////////////////////

export const selectMode = {
  props: ['active', 'stack'],
  setup(props, { emit }) {
    handleActive(props, [NumberKeyHandler, ArrowHorizontalKeyHandler]);

    const children = reactive([
      {
        component: "d-squareElem",
        props:{
          text: "Play Game",
          icon: "/assets/img/dart.svg",
        },
        onClick: () => {
          emit("resolve", "play");
        }
      }
    ]);
    const canvas = ref([]);
    return { children }
  },
  template: html`
    <d-list v-if="active" type="horizontal" :withshortkey="true" :elements="children" />
  `
}


export const selectTournament = {
  props: ['tournaments', 'active', 'stack'],
  setup(props, { emit }) {
    handleActive(props, [NumberKeyHandler, ArrowVerticalKeyHandler]);

    const children = computed(() => {
      const items = [];
      for (let i in props.tournaments){
        const tournament = props.tournaments[i];
        items.push({
          component: "d-plainElem",
          props: {
            text: tournament.title,
          },
          onClick: () => {
            emit("resolve", tournament.id);
          }
        })
      }
      items.push({
        component: "d-plainElem",
        props: {
          text: "Back",
          class: "back"
        },
        onClick: () => {
          emit("reject");
        }
      });
      return items;
    });
    return { children }
  },
  template: html`
  <div v-if="active" class="mainmenu">
    <h1>Select Tournament</h1>
    <d-list  style="width: 65%" :withshortkey="true" :elements="children"/>
  </div>
  `
}


export const selectGame = {
  props: ['games', 'active', 'stack'],
  setup(props, { emit }) {
    handleActive(props, [NumberKeyHandler, ArrowVerticalKeyHandler]);

    const children = computed(() => {
      const items = [];
      items.push({
        component: "d-plainElem",
        props: {
          text: "Create Game",
          class: "new"
        },
        onClick: () => {
          emit("resolve", "create");
        }
      });
      for (let i in props.games){
        const game = props.games[i];
        items.push({
          component: "d-plainElem",
          props: {
            text: game.scorers[0]?.member[0]?.forename + " vs. " + game.scorers[1]?.member[0]?.forename,
          },
          onClick: () => {
            emit("resolve", game.id);
          }
        })
      }
      items.push({
        component: "d-plainElem",
        props: {
          text: "Back",
          class: "back"
        },
        onClick: () => {
          emit("reject");
        }
      });
      return items;
    });
    return { children }
  },
  template: html`
    <div v-if="active" class="mainmenu">
      <h1>Select Game</h1>
      <d-list style="width: 65%" :withshortkey="true" :elements="children"/>
    </div>
  `
}


////////////////////////////////////////////////////////////////////////////////
// State Machine
////////////////////////////////////////////////////////////////////////////////

const stateMachine = (stack) => {
  return {
    0: async (input, reGet) => {
        const [result, error] = await overlayAndGet("d-selectMode", { }, stack, reGet);
        if (error != undefined) {
          return [0, error];
        }
        if (result == "play") {
          return [1, result];
        }
        if (result == "create") {
          // TODO:
          return [1, result];
        }
    },
    1: async (input, reGet) => {
        const tournaments = await getQuery("site.find('seasons').getRunningTournaments", {
          select: {
            title: "page.title",
            id: "page.id",
          }
        });
        const [result, error] = await overlayAndGet("d-selectTournament", { "tournaments": tournaments}, stack, reGet);
        if (error != undefined) {
          popLastElem(stack);
          return [-1, error];
        }
        return [2, result];
    },
    2: async (input, reGet) => {
        const playerInfo = {
          forename: "page.forename",
          surname: "page.surname",
          uuid: "page.uuid",
          // img: "page.pic.toFile?.thumbnail(350).url"
        };
        const games = await getQuery(`site.find('${input}').getRunningGames`, {
          select: {
            title: "page.title",
            id: "page.id",
            uuid: "page.uuid",
            scorers: {
              query: "page.scorers.toStructure",
              select: {
                member: {
                  query: "structureItem.member.toPages",
                  select: playerInfo
                }
              }
            }
          }
        });
        const [result, error] = await overlayAndGet("d-selectGame", {"games": games}, stack, reGet);
        if (error != undefined) {
          popLastElem(stack);
          return [-1, error];
        }
        if (result == "create") {
          // Create Game and redirect
          const ret = await homeAction({
            "action": "createGame",
            "tournament": input
          })
          if (ret.status == "ok") {
            window.setTimeout(() => {
              window.location.href = ret.url;
              return false;
            },1);
          }
          return [undefined, undefined];
        }
        window.setTimeout(() => {
          window.location.href = result;
          return false;
        },1);
        return [undefined, undefined];
    }
  };
}


////////////////////////////////////////////////////////////////////////////////
// Exports
////////////////////////////////////////////////////////////////////////////////

export const homeHandler = async (stack) => {
  const sm = stateMachine(stack);
  powerStateMachine(sm, stack);
}

export const initHomeView = (app) => {
  app.component("d-selectMode", selectMode).component("d-selectTournament", selectTournament).component('d-selectGame', selectGame)
}
