<script lang="ts" setup>
import { ref } from 'vue'
import DiskReader from '@/components/DiskReader.vue'
import HexDump from '@/components/HexDump.vue'
import DiskInfo from '@/components/DiskInfo.vue'

type DiskReadyState = 'empty' | 'read-started' | 'read-success' | 'read-failed'

const diskReadyState = ref<DiskReadyState>('empty')
const diskName = ref('')
const diskTotalBytes = ref(0)
const diskReadBytes = ref(0)
const diskReadError = ref('')
const diskData = ref(new ArrayBuffer(0))

function onReadStart(name: string) {
  console.log(`Reading disk from ${name}`)
  diskReadyState.value = 'read-started'
  diskName.value = name
  diskReadBytes.value = 0
  diskTotalBytes.value = -1
}

function onReadSuccess(data: ArrayBuffer) {
  console.log('Disk read succeeded')
  diskReadyState.value = 'read-success'
  diskData.value = data
}

function onReadError(message: string) {
  console.log('Disk read failed: ' + message)
  diskData.value = new ArrayBuffer(0)
  diskReadError.value = message
  diskReadyState.value = 'read-failed'
  diskReadBytes.value = -1
  diskTotalBytes.value = -1
}

function onReadProgress(read: number, total: number) {
  diskReadBytes.value = read
  diskTotalBytes.value = total
}
</script>

<template>
  <nav>
    <a href="/#/">Home</a>
  </nav>
  <h1>Playground</h1>
  <p>This is my playground for testing out my code.</p>
  <p>
    <strong><em>WARNING!!!</em> Use at your own risk!</strong>
  </p>
  <section>
    <h2>Disk Read</h2>
    <div class="cols">
      <DiskReader
        @error="onReadError"
        @progress="onReadProgress"
        @start="onReadStart"
        @success="onReadSuccess"
      />
      <div v-if="diskReadyState === 'read-started'">
        {{ diskName }} reading
        <progress :max="diskTotalBytes" :value="diskReadBytes">
          {{ ((diskReadBytes / diskTotalBytes) * 100.0).toFixed(2) }} %
        </progress>
        {{ ((diskReadBytes / diskTotalBytes) * 100.0).toFixed(2) }} %
      </div>
      <div v-else-if="diskReadyState === 'read-success'">{{ diskName }} loaded</div>
      <div v-else-if="diskReadyState === 'read-failed'">
        error reading disk: {{ diskReadError }}
      </div>
      <div v-else>No disk loaded</div>
    </div>
  </section>
  <section>
    <h2>Disk Hex Dump</h2>
    <HexDump :buffer="diskData" />
  </section>
  <section>
    <h2>Disk Info</h2>
    <DiskInfo :data="diskData" />
  </section>
</template>

<style scoped>
.cols {
  display: flex;
  flex-direction: row;
  align-items: baseline;
  gap: 1em;
}
</style>
