<template>
  <span>
    {{adjValue === null ? '' : adjValue.toPrecision(5)}}
    <v-btn v-if="showBtn && adjValue!==null" size="small" variant="text" class="ml-0 px-0"
         @click="flipInversionPreference(s.chainId, base, quote)">
      {{pair}}
    </v-btn>
  </span>
  <!--  todo optional pair label and inversion button -->
</template>

<script setup>
import {usePrefStore, useStore} from "@/store/store";
import {computed} from "vue";
import {getToken} from "@/blockchain/token.js";
import {flipInversionPreference, inversionPreference} from "@/misc.js";

const props = defineProps(['value', 'base', 'quote', 'showBtn'])

const s = useStore()

async function token(obj) {
  if (!obj) return null
  return obj.a ? obj : await getToken(s.chainId, obj)
}

const base = await token(props.base)
const quote = await token(props.quote)

const adjValue = computed(() => props.value === null || props.value === undefined ? null : pairPrice(s.chainId, base, quote, props.value))

const pair = computed(() => {
  return inversionPreference(s.chainId, base, quote) ? quote.s + '/' + base.s : base.s + '/' + quote.s
})


function pairPrice(chainId, baseToken, quoteToken, price) {
    if (price === null || price === undefined)
        return null
    const decimals = quoteToken.d - baseToken.d
    if (decimals >= 0)
        price /= 10 ** decimals
    else
        price *= 10 ** -decimals
    const pref = inversionPreference(chainId, baseToken, quoteToken);
    if (pref)
        price = 1 / price
    return price
}


</script>

<style scoped lang="scss">
@use "src/styles/vars" as *;

</style>
