<template>
  <div id="container" class="pageChiefCenter">
    <TopBackBar title="사령부" reloadable @reload="reloadTable" />

    <div
      id="mainTable"
      v-if="chiefList !== undefined"
      :class="`${targetIsMe ? 'targetIsMe' : 'targetIsNotMe'}`"
    >
      <template v-for="(chiefLevel, vidx) in [12, 10, 8, 6, 11, 9, 7, 5]" :key="chiefLevel">
        <div
          v-if="vidx % 4 == 0"
          :class="[
            'turnIdx',
            vidx == 0 && !targetIsMe ? undefined : 'only1000px',
          ]"
        >
          <div :class="['subRows', 'bg0']" :style="mainTableGridRows">
            <div class="bg1">&nbsp;</div>
            <div
              v-for="idx in maxChiefTurn"
              :class="[`turnIdxLeft`, 'align-self-center', 'center']"
              :key="idx"
            >{{ idx }}</div>
          </div>
        </div>
        <div
          v-for="(officer, idx) in [chiefList[chiefLevel]]"
          :key="idx"
          :class="[`${viewTarget == chiefLevel ? '' : 'only1000px'}`]"
        >
          <TopItem
            v-if="officerLevel != chiefLevel"
            :style="mainTableGridRows"
            :officer="officer"
            :maxTurn="maxChiefTurn"
            :turnTerm="turnTerm"
          />
          <ChiefReservedCommand
            v-else
            :serverNick="serverNick"
            :mapName="mapName"
            :unitSet="unitSet"
            :key="idx"
            :targetIsMe="targetIsMe"
            :year="year"
            :month="month"
            :turn="officer.turn"
            :turnTerm="turnTerm"
            :commandList="unwrap(commandList)"
            :turnTime="officer.turnTime"
            :maxTurn="maxChiefTurn"
            :maxPushTurn="Math.floor(maxChiefTurn / 2)"
            :date="date"
            @raiseReload="reloadTable()"
            :officer="officer"
            :timeDiff="timeDiff"
          />
        </div>
        <div
          v-if="vidx % 4 == 3"
          :class="[
            'turnIdx',
            vidx == 7 && !targetIsMe ? undefined : 'only1000px',
          ]"
        >
          <div :class="['subRows', 'bg0']" :style="mainTableGridRows">
            <div class="bg1">&nbsp;</div>
            <div
              v-for="idx in maxChiefTurn"
              :class="[`turnIdxRight`, 'align-self-center', 'center']"
              :key="idx"
            >{{ idx }}</div>
          </div>
        </div>
      </template>
    </div>
  </div>
  <div id="bottomChiefBox" v-if="chiefList">
    <div id="bottomChiefList" class="c-bg2">
      <template v-for="(chiefLevel, vidx) in [12, 10, 8, 6, 11, 9, 7, 5]" :key="chiefLevel">
        <div class="turnIdx subRows bg0" :style="subTableGridRows" v-if="vidx % 4 == 0">
          <div class="bg1" style="grid-row: 1/3"></div>
          <div v-for="idx in maxChiefTurn" :class="[`turnIdxLeft`]" :key="idx">{{ idx }}</div>
        </div>
        <BottomItem
          :chiefLevel="chiefLevel"
          :chiefList="chiefList"
          :style="subTableGridRows"
          :isMe="chiefLevel == officerLevel"
          @click="viewTarget = chiefLevel"
        />
        <div class="turnIdx subRows bg0" :style="subTableGridRows" v-if="vidx % 4 == 3">
          <div class="bg1" style="grid-row: 1/3"></div>
          <div v-for="idx in maxChiefTurn" :class="`turnIdxRight`" :key="idx">{{ idx }}</div>
        </div>
      </template>
    </div>
  </div>
  <div id="bottomBar">
    <BottomBar />
  </div>
</template>
<script lang="ts">
declare const staticValues: {
  serverNick: string,
  mapName: string,
  unitSet: string,
}
</script>
<script lang="ts" setup>
import "@scss/common/bootstrap5.scss";
import "@scss/game_bg.scss";
import "../../css/config.css";

import { computed, defineProps, reactive, ref, toRefs, watch } from "vue";
import ChiefReservedCommand from "@/components/ChiefReservedCommand.vue";
import TopBackBar from "@/components/TopBackBar.vue";
import BottomBar from "@/components/BottomBar.vue";
import VueTypes from "vue-types";
import { isString } from "lodash";
import { entriesWithType } from "./util/entriesWithType";
import { parseTime } from "./util/parseTime";
import TopItem from "@/ChiefCenter/TopItem.vue";
import BottomItem from "@/ChiefCenter/BottomItem.vue";
import type { ChiefResponse, OptionalFull } from "./defs";
import { SammoAPI } from "./SammoAPI";
import { unwrap } from "@/util/unwrap";

const {
  serverNick,
  mapName,
  unitSet,
} = staticValues;

const props = defineProps({
  maxChiefTurn: VueTypes.number.isRequired,
})

const tableObj = reactive<Omit<OptionalFull<ChiefResponse>, "result">>({
  lastExecute: undefined,
  year: undefined,
  month: undefined,
  turnTerm: undefined,
  date: undefined,
  chiefList: undefined,
  isChief: undefined,
  autorun_limit: undefined,
  officerLevel: undefined,
  commandList: undefined,
  mapName: undefined,
  unitSet: undefined,
});

const {
  year,
  month,
  turnTerm,
  date,
  chiefList,
  officerLevel,
  commandList,
} = toRefs(tableObj);

const viewTarget = ref<number | undefined>();

const targetIsMe = ref<boolean>(false);
watch(viewTarget, (val) => {
  console.log("targetChange!", val, targetIsMe);
  if (val === undefined) {
    targetIsMe.value = false;
    return;
  }
  if (tableObj.officerLevel === undefined) {
    targetIsMe.value = false;
  }
  targetIsMe.value = val === tableObj.officerLevel;
  console.log("result", targetIsMe.value);
});

const timeDiff = ref(0);
async function reloadTable(): Promise<void> {
  try {
    const response =
      await SammoAPI.NationCommand.GetReservedCommand<ChiefResponse>();
    console.log(response);
    for (const [key, value] of entriesWithType(response)) {
      if (key === "result") {
        continue;
      }

      if (key === "officerLevel") {
        if (value < 5) {
          tableObj.officerLevel = undefined;
        } else {
          tableObj.officerLevel = value as number;
        }
        continue;
      }

      //HACK:
      tableObj[key as unknown as "year"] = value as unknown as undefined;
    }

    const serverNowObj = parseTime(response.date);
    const clientNowObj = new Date();
    timeDiff.value = serverNowObj.getTime() - clientNowObj.getTime();

    if (viewTarget.value === undefined) {
      if (!tableObj.officerLevel) {
        viewTarget.value = 12;
      } else {
        viewTarget.value = tableObj.officerLevel;
      }
    }
  } catch (e) {
    if (isString(e)) {
      alert(e);
    }
    console.error(e);
    return;
  }
}

const mainTableGridRows = computed(() => {
  return {
    gridTemplateRows: `24px repeat(${props.maxChiefTurn}, 30px)`,
  };
});

const subTableGridRows = computed(() => {
  return {
    gridTemplateRows: `36px repeat(${props.maxChiefTurn + 1}, 1fr)`,
  };
});

void reloadTable();


</script>
<style lang="scss">
@import "@scss/chiefCenter.scss";
</style>