import { jsx as _jsx } from "react/jsx-runtime";
import { createContext, useContext, useEffect, useMemo, useState } from "react";
import { unstable_serialize, useAccount, useMutation, useSWRConfig, utils } from "@orderly.network/hooks";
export const TPSLOrderRowContext = /*#__PURE__*/ createContext({});
export const useTPSLOrderRowContext = ()=>{
    return useContext(TPSLOrderRowContext);
};
export const TPSLOrderRowProvider = (props)=>{
    const [position, setPosition] = useState();
    const [doDeleteOrder] = useMutation("/v1/algo/order", "DELETE");
    const [doUpdateOrder] = useMutation("/v1/algo/order", "PUT");
    const config = useSWRConfig();
    const { state } = useAccount();
    const positionKey = useMemo(()=>{
        return unstable_serialize(()=>[
                "/v1/positions",
                state.accountId
            ]);
    }, [
        state.accountId
    ]);
    const onCancelOrder = async (order)=>{
        return doDeleteOrder(null, {
            order_id: order.algo_order_id,
            symbol: order.symbol
        });
    };
    const onUpdateOrder = async (order, params)=>{
        ;
        return doUpdateOrder({
            order_id: order.algo_order_id,
            child_orders: order.child_orders.map((order)=>({
                    order_id: order.algo_order_id,
                    quantity: params.order_quantity
                }))
        });
    };
    const getRelatedPosition = (symbol)=>{
        const positions = config.cache.get(positionKey);
        return positions?.data.rows.find((p)=>p.symbol === symbol);
    };
    const { sl_trigger_price, tp_trigger_price } = useMemo(()=>{
        if (!("algo_type" in props.order) || !Array.isArray(props.order.child_orders)) {
            return {};
        }
        return utils.findTPSLFromOrder(props.order);
    }, [
        props.order
    ]);
    useEffect(()=>{
        if ("algo_type" in props.order) {
            const position = getRelatedPosition(props.order.symbol);
            if (position) {
                setPosition(position);
            }
        }
    }, [
        props.order.symbol
    ]);
    return /*#__PURE__*/ _jsx(TPSLOrderRowContext.Provider, {
        value: {
            order: props.order,
            sl_trigger_price,
            tp_trigger_price,
            onCancelOrder,
            onUpdateOrder,
            getRelatedPosition,
            position
        },
        children: props.children
    });
};

//# sourceMappingURL=tpslOrderRowContext.js.map