import Decimal from "decimal.js";
import { useCallback } from "react";
import {
  HitoBitSymbolMarketLotSizeFilter,
  HitoBitSymbolPriceFilter,
} from "../services";
import { useMarkets } from "./useMarkets";

const useStepSize = (symbol?: string, type?: "limit" | "market") => {
  const { getSymbolMarketDetails } = useMarkets();
  const targetMarket = getSymbolMarketDetails(symbol);

  const toStepSize = useCallback(
    (value: number | string | Decimal, shouldRoundUp = false) => {
      const stepSize = (
        targetMarket?.filters?.find(({ filterType }) =>
          type === "market"
            ? filterType === "MARKET_LOT_SIZE"
            : filterType === "LOT_SIZE",
        ) as HitoBitSymbolMarketLotSizeFilter
      )?.stepSize;

      if (stepSize !== undefined && value !== "") {
        if (shouldRoundUp) {
          return new Decimal(value)
            .toNearest(stepSize, Decimal.ROUND_UP)
            .toString();
        }
        return new Decimal(value)
          .toNearest(stepSize, Decimal.ROUND_DOWN)
          .toString();
      }
      return value.toString();
    },
    [targetMarket, type],
  );
  const toTickSize = useCallback(
    (value: number | Decimal | string, passedSymbol?: string) => {
      const selectedMarketTicker = passedSymbol
        ? getSymbolMarketDetails(passedSymbol)
        : targetMarket;
      const tickSize = (
        selectedMarketTicker?.filters?.find(
          ({ filterType }) => filterType === "PRICE_FILTER",
        ) as HitoBitSymbolPriceFilter
      )?.tickSize;

      const _tickSize =
        tickSize !== undefined ? (tickSize >= 1 ? 1 : tickSize) : undefined;

      if (_tickSize !== undefined && value !== "") {
        return new Decimal(value)
          .div(_tickSize)
          .floor()
          .mul(_tickSize)
          .toString();
      }
      return value.toString();
    },
    [getSymbolMarketDetails, targetMarket],
  );

  return { toStepSize, toTickSize };
};

export { useStepSize };
