<template>
  <span v-if="route">{{price}}</span>
</template>

<script setup>
import {useOrderStore, useStore} from "@/store/store";
import {subPrices, unsubPrices, WIDE_PRICE_FORMAT} from "@/blockchain/prices.js";
import {computed, onBeforeUnmount} from "vue";
import {FixedNumber} from "ethers";
import {subOHLCs} from "@/blockchain/ohlcs.js";
import {routeInverted} from "@/misc.js";

const s = useStore()
const os = useOrderStore()

const props = defineProps({
  route: {type: Object, required:false},
  inverted: {type: Boolean, required:false},
  precision: {type: Number, default:5, required:false},
})

const route = computed(()=>props.route ? props.route : os.route)

const price = computed(()=>{
  if( !route.value )
    return ''
  const routeKey = [route.value.chainId, route.value.pool]
  if( !(routeKey in s.poolPrices) )
    return ''
  let p = s.poolPrices[routeKey]
  // console.log('pool price is',typeof p, p)
  if( !p )
    return ''
  p = FixedNumber.fromString(p, WIDE_PRICE_FORMAT).toUnsafeFloat()
  const inverted = props.inverted === undefined ? routeInverted(route.value) : props.inverted;
  if( inverted )
    p = 1/p
  return p.toPrecision(props.precision)
})

if( route.value ) {
  subPrices([route.value])
  subOHLCs( s.chainId, [[route.value.pool,'1D']])
}
else
  console.log('route is empty: no price')

onBeforeUnmount(() => {
  if( route.value )
    unsubPrices([route.value])
})


</script>

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