<template>
  <ChartJs :snatchedPositions="snatchPositions.map(obj => obj.id)" :positions="activePositions" :dark="darkTheme"></ChartJs>
</template>

<script setup lang="ts">
import ChartJs from '@/components/chart/ChartJs.vue';
import { weiToNumber } from 'kraiken-lib/format';
import { computed, ref } from 'vue';
import { useStatCollection } from '@/composables/useStatCollection';
import { useStake } from '@/composables/useStake';
import { usePositions, type Position } from '@/composables/usePositions';
import { useDark } from '@/composables/useDark';
import { useWallet } from '@/composables/useWallet';
import { DEFAULT_CHAIN_ID } from '@/config';
const { darkTheme } = useDark();

const wallet = useWallet();
const initialChainId = wallet.account.chainId ?? DEFAULT_CHAIN_ID;
const { activePositions } = usePositions(initialChainId);
const stake = useStake();
const statCollection = useStatCollection(initialChainId);
const minStake = computed(() => statCollection.minStake ?? 0n);
const minStakeAmount = computed(() => {
  return weiToNumber(minStake.value, 18);
});
const ignoreOwner = ref(false);

const taxRate = ref<number>(1.0);
const snatchPositions = computed(() => {
  if (
    weiToNumber(statCollection.outstandingStake, 18) + stake.stakingAmountNumber <=
    weiToNumber(statCollection.kraikenTotalSupply, 18) * 0.2
  ) {
    return [];
  }
  //Differenz aus outstandingSupply und totalSupply bestimmen, wie viel HARB kann zum Snatch verwendet werden
  const difference =
    weiToNumber(statCollection.outstandingStake, 18) +
    stake.stakingAmountNumber -
    weiToNumber(statCollection.kraikenTotalSupply, 18) * 0.2;

  //Division ohne Rest, um zu schauen wie viele Positionen gesnatched werden könnten
  const snatchAblePositionsCount = Math.floor(difference / minStakeAmount.value);

  //wenn mehr als 0 Positionen gesnatched werden könnten, wird geschaut wie viele Positionen in Frage kommen
  if (snatchAblePositionsCount > 0) {
    const snatchAblePositions = activePositions.value.filter((obj: Position) => {
      if (ignoreOwner.value) {
        return obj.taxRatePercentage < taxRate.value;
      }
      return obj.taxRatePercentage < taxRate.value && !obj.iAmOwner;
    });
    const slicedArray = snatchAblePositions.slice(0, snatchAblePositionsCount);
    return slicedArray;
  }

  return [];
});
</script>
