<template>
  <div class="commandPad">
    <div class="col alert alert-dark m-0 p-1 center">
      <h4 class="m-0">명령 목록</h4>
    </div>
    <div class="row gx-0 commandSelectFormAnchor">
      <div class="col-3 d-grid">
        <BButton variant="primary">편집</BButton>
      </div>
      <div class="col-6 d-grid">
        <BButton variant="light" @click="toggleForm($event)" :style="{color: 'black'}">{{ selectedCommand.simpleName }} ▾</BButton>
      </div>
      <div class="col-3 d-grid">
        <BButton @click="reserveCommand()" variant="primary">실행</BButton>
      </div>
    </div>
    <div class="row gx-1">
      <div class="col d-grid">
        <BDropdown left text="턴 선택">
          <BDropdownItem @click="selectTurn()">해제</BDropdownItem>
          <BDropdownItem @click="selectAll(true)">모든턴</BDropdownItem>
          <BDropdownItem @click="selectStep(0, 2)">홀수턴</BDropdownItem>
          <BDropdownItem @click="selectStep(1, 2)">짝수턴</BDropdownItem>
          <BDropdownDivider></BDropdownDivider>

          <BDropdownText v-for="spanIdx in [3, 4, 5, 6, 7]" :key="spanIdx">
            {{ spanIdx }}턴 간격
            <br />
            <BButtonGroup>
              <BButton
                class="ignoreMe"
                v-for="beginIdx in spanIdx"
                :key="beginIdx"
                @click="selectStep(beginIdx - 1, spanIdx)"
              >{{ beginIdx }}</BButton>
            </BButtonGroup>
          </BDropdownText>
        </BDropdown>
      </div>
      <div
        class="col alert alert-primary m-0 p-0"
        style="
          text-align: center;
          display: flex;
          justify-content: center;
          align-items: center;
        "
      >{{ formatTime(serverNow, "HH:mm:ss") }}</div>
      <div class="col d-grid">
        <BDropdown right text="반복">
          <BDropdownItem
            v-for="turnIdx in maxPushTurn"
            :key="turnIdx"
            @click="repeatGeneralCommand(turnIdx)"
          >{{ turnIdx }}턴</BDropdownItem>
        </BDropdown>
      </div>
    </div>

    <div class="commandTable">
      <DragSelect
        :style="rowGridStyle"
        attribute="turnIdx"
        @dragStart="isDragToggle = true"
        @dragDone="
  isDragToggle = false;
toggleTurn(...$event);
        "
        v-slot="{ selected }"
      >
        <div
          v-for="(turnObj, turnIdx) in reservedCommandList.slice(
            0,
            viewMaxTurn
          )"
          :turnIdx="turnIdx"
          :key="turnIdx"
          class="idx_pad center d-grid"
        >
          <BButton
            size="sm"
            :variant="
              (isDragToggle && selected.has(`${turnIdx}`)) ? 'light' :
                turnList.has(turnIdx)
                  ? 'info'
                  : turnList.size == 0 && prevTurnList.has(turnIdx)
                    ? 'success'
                    : 'primary'
            "
          >{{ turnIdx + 1 }}</BButton>
        </div>
      </DragSelect>
      <DragSelect
        :style="rowGridStyle"
        attribute="turnIdx"
        @dragStart="isDragSingle = true"
        @dragDone="
  isDragSingle = false;
selectTurn(...$event);
        "
        v-slot="{ selected }"
      >
        <div
          v-for="(turnObj, turnIdx) in reservedCommandList.slice(
            0,
            viewMaxTurn
          )"
          :key="turnIdx"
          height="24"
          class="month_pad center"
          :turnIdx="turnIdx"
          :style="{
            'white-space': 'nowrap',
            'font-size': `${Math.min(
              14,
              (75 / (`${turnObj.year ?? 1}`.length + 8)) * 1.8
            )}px`,
            overflow: 'hidden',
            color:
              isDragSingle && selected.has(`${turnIdx}`) ? 'cyan' : undefined,
          }"
        >
          {{ turnObj.year ? `${turnObj.year}年` : "" }}
          {{ turnObj.month ? `${turnObj.month}月` : "" }}
        </div>
      </DragSelect>
      <div :style="rowGridStyle">
        <div
          v-for="(turnObj, turnIdx) in reservedCommandList.slice(
            0,
            viewMaxTurn
          )"
          :key="turnIdx"
          class="time_pad center"
          :style="{
            backgroundColor: 'black',
            whiteSpace: 'nowrap',
            overflow: 'hidden',
          }"
        >{{ turnObj.time }}</div>
      </div>
      <div :style="rowGridStyle">
        <div
          v-for="(turnObj, turnIdx) in reservedCommandList.slice(
            0,
            viewMaxTurn
          )"
          :key="turnIdx"
          class="turn_pad center"
          @click="chooseCommand(turnObj.action)"
        >
          <span
            class="turn_text"
            :style="turnObj.style"
            v-b-tooltip.hover
            :title="turnObj.tooltip"
            v-html="turnObj.brief"
          ></span>
        </div>
      </div>
    </div>
    <div class="row gx-1">
      <div class="col d-grid">
        <BDropdown right split text="당기기" @click="pullGeneralCommandSingle">
          <BDropdownItem
            v-for="turnIdx in maxPushTurn"
            :key="turnIdx"
            @click="pushGeneralCommand(-turnIdx)"
          >{{ turnIdx }}턴</BDropdownItem>
        </BDropdown>
      </div>
      <div class="col d-grid">
        <BDropdown right split text="미루기" @click="pushGeneralCommandSingle">
          <BDropdownItem
            v-for="turnIdx in maxPushTurn"
            :key="turnIdx"
            @click="pushGeneralCommand(turnIdx)"
          >{{ turnIdx }}턴</BDropdownItem>
        </BDropdown>
      </div>
      <div class="col d-grid">
        <BButton @click="toggleViewMaxTurn">
          {{
            flippedMaxTurn == viewMaxTurn ? "펼치기" : "접기"
          }}
        </BButton>
      </div>
    </div>
  </div>
  <CommandSelectForm
    :commandList="commandList"
    anchor=".commandSelectFormAnchor"
    ref="commandSelectForm"
    @on-close="chooseCommand($event)"
  />
</template>

<script lang="ts">
declare const staticValues: {
  maxTurn: number,
  maxPushTurn: number,
  commandList: {
    category: string;
    values: CommandItem[];
  }[],
  serverNow: string,
}
</script>

<script lang="ts" setup>
import addMilliseconds from "date-fns/esm/addMilliseconds";
import addMinutes from "date-fns/esm/addMinutes";
import { isString, range } from "lodash";
import { stringifyUrl } from "query-string";
import { onMounted, ref, watch } from "vue";
import { formatTime } from "@util/formatTime";
import { joinYearMonth } from "@util/joinYearMonth";
import { mb_strwidth } from "@util/mb_strwidth";
import { parseTime } from "@util/parseTime";
import { parseYearMonth } from "@util/parseYearMonth";
import DragSelect from "@/components/DragSelect.vue";
import { SammoAPI } from "./SammoAPI";
import type { CommandItem } from "@/defs";
import CommandSelectForm from "@/components/CommandSelectForm.vue";
import { BButton, BButtonGroup, BDropdownItem, BDropdown, BDropdownText, BDropdownDivider } from "bootstrap-vue-3";

type TurnObj = {
  action: string;
  brief: string;
  arg: null | [] | Record<string, number | string | number[] | string[]>;
};

type TurnObjWithTime = TurnObj & {
  time: string;
  year?: number;
  month?: number;
  tooltip?: string;
  style?: Record<string, unknown>;
};

type ReservedCommandResponse = {
  result: true;
  turnTime: string;
  turnTerm: number;
  year: number;
  month: number;
  date: string;
  turn: TurnObj[];
  autorun_limit: null | number;
};


const {
  maxTurn,
  maxPushTurn,
  commandList,
} = staticValues;


const listReqArgCommand = new Set<string>();
const serverNow = ref(parseTime(staticValues.serverNow));
const clientNow = ref(new Date());
const timeDiff = ref(serverNow.value.getTime() - clientNow.value.getTime());
const selectedCommand = ref(staticValues.commandList[0].values[0]);
const commandSelectForm = ref<InstanceType<typeof CommandSelectForm> | null>(null);

for (const commandCategories of commandList) {
  if (!commandCategories.values) {
    continue;
  }
  for (const commandObj of commandCategories.values) {
    if (!commandObj.reqArg) {
      continue;
    }
    listReqArgCommand.add(commandObj.value);
  }
}

function toggleForm($event: Event): void{
  $event.preventDefault();

  const form = commandSelectForm.value;
  if(!form){
    return;
  }
  form.toggle();
}

function isDropdownChildren(e?: Event): boolean {
  if (!e) {
    return false;
  }
  if (!e.target) {
    return false;
  }
  if (
    (e.target as HTMLElement).classList.contains("dropdown-item") ||
    (e.target as HTMLElement).classList.contains("dropdown-toggle-split") ||
    (e.target as HTMLElement).classList.contains("ignoreMe")
  ) {
    return true;
  }
  return false;
}


setTimeout(() => {
  updateNow();
}, 1000 - serverNow.value.getMilliseconds());


const emptyTurn: TurnObjWithTime[] = Array.from<TurnObjWithTime>({
  length: staticValues.maxTurn,
}).fill({
  arg: null,
  brief: "",
  action: "",
  year: undefined,
  month: undefined,
  time: "",
});

const prevTurnList = ref(new Set([0]));
const turnList = ref(new Set<number>());
const reservedCommandList = ref(emptyTurn);

const flippedMaxTurn = 15;
const viewMaxTurn = ref(flippedMaxTurn);
const rowGridStyle = ref({
  display: "grid",
  gridTemplateRows: `repeat(${viewMaxTurn.value}, 29.4px)`,
});

watch(viewMaxTurn, (val) => {
  rowGridStyle.value.gridTemplateRows = `repeat(${val}, 29.4px)`;
});

const isDragSingle = ref(false);
const isDragToggle = ref(false);

const invCommandMap: Record<string, CommandItem> = {};
for (const category of commandList) {
  for (const command of category.values) {
    invCommandMap[command.value] = command;
  }
}


function updateNow() {
  serverNow.value = addMilliseconds(new Date(), timeDiff.value);
  setTimeout(() => {
    updateNow();
  }, 1000 - serverNow.value.getMilliseconds());
}

function toggleTurn(...reqTurnList: number[] | string[]) {
  for (let turnIdx of reqTurnList) {
    if (isString(turnIdx)) {
      turnIdx = parseInt(turnIdx);
    }
    if (turnList.value.has(turnIdx)) {
      turnList.value.delete(turnIdx);
    } else {
      turnList.value.add(turnIdx);
    }
  }
}

function selectTurn(...reqTurnList: number[] | string[]) {
  turnList.value.clear();
  for (const turnIdx of reqTurnList) {
    if (isString(turnIdx)) {
      turnList.value.add(parseInt(turnIdx));
    } else {
      turnList.value.add(turnIdx);
    }
  }
}

function selectAll(e: Event | true) {
  //NOTE: split 구현에 버그가 있어서, 수동으로 구분해야함
  if (e !== true && isDropdownChildren(e)) {
    return;
  }

  if (turnList.value.size * 3 > maxTurn) {
    turnList.value.clear();
  } else {
    for (let i = 0; i < maxTurn; i++) {
      turnList.value.add(i);
    }
  }
}

function selectStep(begin: number, step: number) {
  turnList.value.clear();
  for (const idx of range(0, maxTurn)) {
    if ((idx - begin) % step == 0) {
      turnList.value.add(idx);
    }
  }
}

function toggleViewMaxTurn() {
  if (viewMaxTurn.value == flippedMaxTurn) {
    viewMaxTurn.value = maxTurn;
  } else {
    viewMaxTurn.value = flippedMaxTurn;
  }
}

async function repeatGeneralCommand(amount: number) {
  try {
    await SammoAPI.Command.RepeatCommand({ amount });
  } catch (e) {
    console.error(e);
    alert(`실패했습니다: ${e}`);
    return;
  }
  await reloadCommandList();
}

async function pushGeneralCommand(amount: number) {
  try {
    await SammoAPI.Command.PushCommand({ amount });
  } catch (e) {
    console.error(e);
    alert(`실패했습니다: ${e}`);
    return;
  }
  await reloadCommandList();
}

function pushGeneralCommandSingle(e: Event) {
  //NOTE: split 구현에 버그가 있어서, 수동으로 구분해야함
  if (isDropdownChildren(e)) {
    return;
  }
  void pushGeneralCommand(1);
}

function pullGeneralCommandSingle(e: Event) {
  //NOTE: split 구현에 버그가 있어서, 수동으로 구분해야함
  if (isDropdownChildren(e)) {
    return;
  }
  void pushGeneralCommand(-1);
}

async function reloadCommandList() {
  let result: ReservedCommandResponse;
  try {
    result = await SammoAPI.Command.GetReservedCommand();
  } catch (e) {
    console.error(e);
    alert(`실패했습니다: ${e}`);
    return;
  }

  let yearMonth = joinYearMonth(result.year, result.month);

  const turnTime = parseTime(result.turnTime);
  let nextTurnTime = new Date(turnTime);

  const autorunLimitYearMonth = result.autorun_limit ?? yearMonth - 1;
  const [autorunLimitYear, autorunLimitMonth] = parseYearMonth(
    autorunLimitYearMonth
  );

  reservedCommandList.value = [];
  for (const obj of result.turn) {
    const [year, month] = parseYearMonth(yearMonth);
    let tooltip: string[] = [];
    let style: Record<string, unknown> = {};

    const brief = obj.brief;

    if (yearMonth <= autorunLimitYearMonth) {
      if (obj.brief == "휴식") {
        obj.brief = "휴식<small>(자율 행동)</small>";
      }
      style.color = "#aaffff";

      tooltip.push(
        `자율 행동 기간: ${autorunLimitYear}년 ${autorunLimitMonth}월까지`
      );
    }

    if (mb_strwidth(brief) > 22) {
      tooltip.push(brief);
    }

    reservedCommandList.value.push({
      ...obj,
      year,
      month,
      time: formatTime(nextTurnTime, "HH:mm"),
      tooltip: tooltip.length == 0 ? undefined : tooltip.join("\n"),
      style,
    });

    yearMonth += 1;
    nextTurnTime = addMinutes(nextTurnTime, result.turnTerm);
  }

  serverNow.value = parseTime(result.date);
  clientNow.value = new Date();
  timeDiff.value = serverNow.value.getTime() - clientNow.value.getTime();
}

async function reserveCommand() {
  let reqTurnList: number[];
  if (turnList.value.size == 0) {
    reqTurnList = Array.from(prevTurnList.value.values());
  } else {
    reqTurnList = Array.from(turnList.value.values());
  }

  if (reqTurnList.length == 0) {
    reqTurnList.push(0);
  }

  const commandName = selectedCommand.value.value;

  if (listReqArgCommand.has(commandName)) {
    document.location.href = stringifyUrl({
      url: "v_processing.php",
      query: {
        command: commandName,
        turnList: reqTurnList.join("_"),
      },
    });
    return;
  }

  try {
    await SammoAPI.Command.ReserveCommand({
      turnList,
      action: commandName,
    });

    if (turnList.value.size > 0) {
      prevTurnList.value.clear();
      for (const v of turnList.value) {
        prevTurnList.value.add(v);
      }
      turnList.value.clear();
    }
  } catch (e) {
    console.error(e);
    alert(`실패했습니다: ${e}`);
    return;
  }
  await reloadCommandList();
}

function chooseCommand(val?: string) {
  if (!val) {
    return;
  }
  selectedCommand.value = invCommandMap[val];
}

onMounted(() => {
  void reloadCommandList();
});

</script>
<style lang="scss">
@use "sass:color";

@import "@scss/common/break_500px.scss";
@import "@scss/common/variables.scss";
@import "@scss/common/bootswatch_custom_variables.scss";
@import "@scss/game_bg.scss";

.commandPad {
  background-color: $gray-900;
}

.commandTable {
  width: 100%;
  display: grid;
  grid-template-columns: minmax(30px, 1fr) minmax(75px, 2.5fr) minmax(40px, 1fr) 5fr;
  //30, 70, 37.65, 160
}

@include media-1000px {
  .commandPad {
    margin-left: 10px;

    .turn_pad {
      overflow: hidden;
      text-overflow: ellipsis;
    }
    .multiselect__content-wrapper {
      margin-left: calc(-100% / 7 * 2);
      width: calc(100% / 7 * 12);
    }

    .multiselect__single {
      display: inline-block;
      text-overflow: ellipsis;
      white-space: nowrap;
      overflow: hidden;
    }
  }
}

@include media-500px {
  .dropdown-item {
    padding: 8px;
  }

  .commandPad {
    margin-top: 10px;
    margin-bottom: 10px;

    .btn {
      transition: none !important;
    }
  }

  .month_pad,
  .time_pad,
  .turn_pad {
    padding: 6px;
  }
}

.month_pad:hover {
  text-decoration: underline;
  cursor: pointer;
}

.month_pad,
.time_pad,
.turn_pad {
  display: flex;
  justify-content: center;
  align-items: center;
}

.turn_pad {
  white-space: nowrap;
  background-color: $nbase2color;
}

.turn_pad:nth-child(2n) {
  background-color: color.adjust($nbase2color, $lightness: -5%);
}

.turn_pad .turn_text {
  display: inline-block;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}
</style>