import {AnyJson} from '~/types/interfaces'
import {QUERY_TYPE} from "~/types/enums";
import {useFetch, Ref, ref} from '@nuxtjs/composition-api'
import DataProvider from "~/services/data/dataProvider";

/**
 * @category composables/data
 * @class UseImage
 * Use Classe qui va récupérer les Images
 */
export function useImageProvider($dataProvider: DataProvider, $config: AnyJson) {

  /**
   * Récupération d'une image via l'ancienne API
   */
  function getOne(id: number | undefined, imageByDefault: string = '', height: number | undefined = 0, width: number | undefined = 0): AnyJson {
    const imageLoaded: Ref<String> = ref('')

    const {fetchState, fetch} = useFetch(async () => {
        try {
          if (id) {
            imageLoaded.value = await provideImg(id, height, width)
          } else
            throw new Error('id is null')
        } catch (e) {
          if (imageByDefault)
            imageLoaded.value = require(`assets/images/byDefault/${imageByDefault}`)
        }
      }
    )

    return {
      fetch,
      fetchState,
      imageLoaded
    }
  }

  /**
   * retourne l'image demandée
   * @param id
   * @param height
   * @param width
   */
  async function provideImg(id: number, height: number = 0, width: number = 0) {
    return await $dataProvider.invoke({
      type: QUERY_TYPE.IMAGE,
      baseUrl: $config.baseURL_Legacy,
      imgArgs: {
        id: id,
        height: height,
        width: width
      }
    })
  }

  return {
    getOne,
    provideImg
  }
}
