<script setup>
import { watch, shallowRef } from "vue";
import { MetroWidget, VERTICAL } from "jsview";
import Item from "./Item.vue";
import { useRouter } from "vue-router";
const router = useRouter();
let mw = shallowRef(null);
const props = defineProps({
  data: Array,
  name: String,
  onEdge: Function,
  tabId: Number,
});

const direction = VERTICAL;
const width = 1280;
const height = 600;
let initFocusId = shallowRef(0);

const measures = (item) => {
  return {
    width: item.width,
    height: item.height,
    focusable: item.focusable,
    enableTap: true,
  };
};

const itemClick = (index, data) => {
  if (!data.path) {
    console.error("Route path is not defined.");
    return;
  }
  router.push(data.path);
  localStorage.curFocusId = index;
  localStorage.curTab = props.tabId;
};

const _provideData = () => {
  return props.data;
};

if (typeof localStorage.curFocusId !== "undefined") {
  initFocusId.value = parseInt(localStorage.curFocusId);
}
localStorage.curFocusId = 0;
watch(
  () => {
    return props.data;
  },
  () => {
    mw.value?.refreshData(true);
  }
);
</script>

<template>
  <metro-widget
    ref="mw"
    :name="props.name"
    :width="width"
    :height="height"
    :direction="direction"
    :provideData="_provideData"
    :measures="measures"
    :padding="{ left: 10, top: 10, right: 10, bottom: 10 }"
    :onEdge="props.onEdge"
    :initFocusId="initFocusId"
    :touchFlag="1"
  >
    <template #renderItem="{ data, query, onEdge, onAction }">
      <Item
        :style="{
          width: data.width,
          height: data.height,
          backgroundColor: data.backgroundColor,
          color: '#000000',
        }"
        :data="data"
        :query="query"
        :onEdge="onEdge"
        :onAction="onAction"
        :itemClick="itemClick"
      >
        {{ data.name }}
      </Item>
    </template>
  </metro-widget>
</template>
