<template>
  <token-choice v-model="tokenA" class="token-choice mb-1">
    <template v-slot:prepend>
      <v-btn :text="os.buy ? 'Buy' : 'Sell'" :color="os.buy ? 'green' : 'red'"
             variant="outlined" @click="os.buy=!os.buy" class="bs-button"/>
    </template>
  </token-choice>
  <token-choice v-model="tokenB" class="token-choice">
    <template v-slot:prepend>
      <v-btn :text="!os.buy ? 'Buy' : 'Sell'" :color="!os.buy ? 'green' : 'red'"
             variant="outlined" @click="os.buy=!os.buy" class="bs-button"/>
    </template>
  </token-choice>

  <v-chip v-for="r in routes" variant="text">
    {{ s.chain.name }}
    <v-img src="https://upload.wikimedia.org/wikipedia/commons/e/e7/Uniswap_Logo.svg" width="1.5em"/>
    <span class="uniswap-color ml-0 mr-1">v3</span>
    <span>{{ os.pairSymbol }} {{ r.fee / 10000 }}%</span>&nbsp;
    <route-price :route="r" :inverted="routeInverted(r)" class="text-green clickable" @click="os.inverted=!os.inverted"/>
  </v-chip>

  <div v-if="os.routesPending">
    <v-progress-circular indeterminate/>
    Searching for {{ os.pairSymbol }} pools...
  </div>

  <v-alert v-if="!os.route && !os.routesPending" text="No pool found!"/>

</template>

<script setup>
import TokenChoice from "@/components/TokenChoice.vue"
import {useOrderStore, useStore} from "@/store/store";
import RoutePrice from "@/components/RoutePrice.vue";
import {findRoute, routeFinder} from "@/blockchain/route.js";
import {SingletonCoroutine, routeInverted} from "@/misc.js";
import {computed, ref} from "vue";
import {queryHelperContract} from "@/blockchain/contract.js";

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

const tokenA = computed({
  get() {
    return os.tokenA
  },
  set(value) {
    if( !os.tokenA || os.tokenA.a !== value.a ) {
      os.tokenA = value
      routeFinder.invoke()
    }
  }
})
const tokenB = computed({
  get() {
    return os.tokenB
  },
  set(value) {
    if( !os.tokenB || os.tokenB.a !== value.address ) {
      os.tokenB = value
      routeFinder.invoke()
    }
  }
})


const routes = computed({
  get() {
    return os.routes
  },
  set(value) {
    console.log('setting new routes', os.routes, value)
    os.routes = value
  }
})

routeFinder.invoke()


</script>

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

</style>
