<script setup lang='ts'>
import { ref, type PropType, type ComponentObjectPropsOptions } from 'vue'
import { type AxiosInstance } from 'axios'

import { resourceServer, axiosResourceProviders } from '@/main'

interface Props {
  resourceName: string,
  resourceProviderId?: string | number,
  resourceId?: string | null,
}

const props = defineProps<Props>()

/*
const props = defineProps<ComponentObjectPropsOptions<Props>>({
  resourceName: {
    type: String,
    required: true
  },
  resourceId: { type: String},
})
*/
let _class = ref<string>("")
let _title = ref<string>("")

const init = async (props: any) => {
  // Get code at component boot time
  const axiosResourceProvider: AxiosInstance = props.resourceProviderId ? axiosResourceProviders[props.resourceProviderId] : resourceServer
  const url = props.resourceId ? `${props.resourceName}/${props.resourceId}` : props.resourceName 
  await axiosResourceProvider.get(url).then(
    resp => {
      _class.value = `hasResponseStatus status-${resp.status}`
      _title.value = `Response code: ${resp.status} - ${resp.statusText}`
    }
  ).catch(
    err => {
      _class.value = `hasResponseStatus status-${err.response.status}`
      _title.value = `Response code: ${err.response.status} - ${err.response.statusText}`
    }
  )
}

init(props);

</script>

<template>
  <button :class="_class" :title="_title" @click="$emit('getResource', $event)"></button>
</template>
