<script setup>
const axios = inject('axios')
const log_list = ref([])
const current_log = ref('')
const log_content = ref([])
const log_frame = ref(0)
const log_scroll = ref(null)

onMounted(() => {
  axios.get(`${import.meta.env.VITE_HTTP_URL}/debug/log`).then(({ data }) => {
    log_list.value = data
  })
  get_log('runtime.log')
})

function get_log(log) {
  current_log.value = log
  axios.get(`${import.meta.env.VITE_HTTP_URL}/debug/log/${log}`).then(({ data }) => {
    log_frame.value = 0
    log_content.value = data
    log_frame.value = log_content.value.length - 1
  })
}

const screenshot = computed(() => {
  return log_content.value[log_frame.value]?.screenshot
})

const image_url = computed(() => {
  return `${import.meta.env.VITE_HTTP_URL}/debug/screenshot/${screenshot.value}`
})

import IosArrowBack from '@vicons/ionicons4/IosArrowBack'
import IosArrowForward from '@vicons/ionicons4/IosArrowForward'

watch(log_frame, () => {
  log_scroll.value?.scrollTo({ top: 0 })
})
</script>

<template>
  <n-flex style="width: 100%; height: 100%; gap: 0; overflow-y: hidden">
    <n-scrollbar style="width: 220px">
      <n-list hoverable clickable bordered>
        <n-list-item v-for="log in log_list" @click="get_log(log)">{{ log }}</n-list-item>
      </n-list>
    </n-scrollbar>
    <n-flex vertical style="flex: 1; height: 100%; overflow: hidden">
      <h2 style="text-align: center; margin: 0">{{ current_log }}</h2>
      <n-image
        v-if="screenshot"
        :src="image_url"
        :alt="screenshot"
        width="100%"
        style="max-height: 50%"
        object-fit="scale-down"
      />
      <n-scrollbar
        ref="log_scroll"
        style="width: 100%"
        content-style="font-size: 16px; user-select: text; padding: 0 12px"
      >
        <div v-for="line in log_content[log_frame]?.log">
          <code>{{ line }}</code>
        </div>
      </n-scrollbar>
      <n-flex align="center" style="padding: 0 12px 6px">
        <n-slider
          style="flex: 1"
          show-tooltip
          v-model:value="log_frame"
          :min="0"
          :max="log_content.length - 1"
          :format-tooltip="(idx) => log_content[idx]?.time"
        />
        <n-button-group>
          <n-button :disabled="log_frame == 0" @click="log_frame--">
            <template #icon>
              <n-icon><ios-arrow-back /></n-icon>
            </template>
          </n-button>
          <n-button :disabled="log_frame == log_content.length - 1" @click="log_frame++">
            <template #icon>
              <n-icon><ios-arrow-forward /></n-icon>
            </template>
          </n-button>
        </n-button-group>
      </n-flex>
    </n-flex>
  </n-flex>
</template>
