<script lang="ts">
import { defineComponent, ref } from 'vue'
import { Figure } from '../grpc/figure'
import { FigureServiceClient } from '../grpc/figure.client'
import { GrpcWebFetchTransport } from '@protobuf-ts/grpcweb-transport'
import { host } from '../connect'

const plots = ref<Figure[]>([])
const loading = ref(true)
const error = ref<string | null>(null)
var emit = (_: any, ...args: any[]) => {
  console.log('No emit function set', args)
}

export default defineComponent({
  emits: ['figure-selected', 'figure-deselected'],
  data() {
    return {
      selected: [],
      loading: loading,
      plots: plots,
      error,
    }
  },
  setup(_, ctx) {
    console.log('Setup')
    emit = ctx.emit
  },
  async mounted() {
    const transport = new GrpcWebFetchTransport({ baseUrl: host })
    const figureService = new FigureServiceClient(transport)
    const stream = figureService.getFigure({})
    for await (const response of stream.responses) {
      console.log('Got new figure', response)
      plots.value.push(response)
    }
    console.log('Done fetching figures')
    loading.value = false
  },
  watch: {
    selected(newVal: string[], oldVal: string[]) {
      const added = newVal.filter((x) => !oldVal.includes(x))
      const removed = oldVal.filter((x) => !newVal.includes(x))

      for (const uuid of added) {
        console.log('Selected', uuid)
        const plot = plots.value.find((x) => x.uuid === uuid)
        emit('figure-selected', plot)
      }
      for (const uuid of removed) {
        console.log('Deselected', uuid)
        const plot = plots.value.find((x) => x.uuid === uuid)
        emit('figure-deselected', plot)
      }
    },
  },
})
</script>

<template>
  <v-navigation-drawer permanent width="250">
    <v-list>
      <v-list-item title="Available figures" subtitle="Choose some of the figures below" />
    </v-list>
    <v-divider />
    <v-list v-model:selected="selected" select-strategy="leaf" nav>
      <v-list-item v-for="plot in plots" :key="plot.uuid" :value="plot.uuid">
        <v-list-item-title>{{ plot.title }}</v-list-item-title>
        <v-list-item-subtitle class="text-high-emphasis"
          >{{ plot.xLabel }} w/ {{ plot.yLabel }}</v-list-item-subtitle
        >
      </v-list-item>
      <v-skeleton-loader
        type="list-item-two-line"
        v-for="n in 3"
        :key="n"
        v-if="loading"
      ></v-skeleton-loader>
    </v-list>
  </v-navigation-drawer>
</template>

<style scoped></style>
