<script setup>
import { shallowRef, provide, onMounted } from "vue";
import { CONST_MAX_COLUMN, CONST_MAX_AREA_LINE, CONST_COLUMN_MARK, CONST_FILL_NAME_FUNC } from "./constants.js"
import Level0Area from "./Level0Area.vue";
import { useFocusHub } from "jsview";

const focusHubRoot = useFocusHub(); // 获得root的FocusHub

const columnMark = shallowRef(0);
provide(CONST_COLUMN_MARK, columnMark); // 全局行记录器, 同步列信息

const blockFullNames = new Array(CONST_MAX_AREA_LINE * 2 * CONST_MAX_COLUMN);
provide(CONST_FILL_NAME_FUNC, (line, column, fullName)=>{
  // 通过BaseBlock的mount后的异步调用, 完成fullName的填充
  blockFullNames[line * CONST_MAX_COLUMN + column] = fullName;
})

let lineMark = 0;

const onKeyDown = (ev) => {
  // 子节点未处理的按键事件会流向此节点
  let keyUsed = true;
  let focusLine = lineMark;
  switch (ev.keyCode) {
    case 38: // UP
      focusLine--;
      break;
    case 40: // Down
      focusLine++;
      break;
    default:
      keyUsed = false;
  }

  if (keyUsed) {
    // 收到了左右键的处理

    // 防止运动越界
    if (focusLine < 0) {
      focusLine = 0;
    } else if (focusLine >= CONST_MAX_AREA_LINE * 2) {
      focusLine = CONST_MAX_AREA_LINE * 2 - 1;
    }
    lineMark = focusLine; // 记录运动结果

    // 因为focusHub为root型的, 使用fullName(带有NameSpace的全路径)来进行focus
    let fullName = blockFullNames[focusLine * CONST_MAX_COLUMN + columnMark.value];
    console.log(`Do root change focus to name=${fullName}`)
    focusHubRoot.setFocus(fullName);
  }

  return keyUsed; // 其他继续上报, 例如返回键处理
};

focusHubRoot.setFocus("TopNS.L0.C0");

onMounted(()=>{
  columnMark.value = 0;
  lineMark = 0;
});

</script>

<template>
  <jsv-focus-block
      :onAction="{
        onKeyDown,
      }">
    <level-0-area newNameSpace="TopNS" :startLine="0" :style="{top:0}"/>
    <level-0-area newNameSpace="BottomNS" :startLine="CONST_MAX_AREA_LINE" :style="{top:120 * CONST_MAX_AREA_LINE + 20}"/>
  </jsv-focus-block>
</template>

<style scoped>

</style>