// trade_order_blocks.js

/**
 * Trade Order Blocks Category Definitions
 *
 * This file defines a set of trade order-related blocks for Blockly. These blocks
 * enable users to execute trade actions (Buy/Sell) with various parameters and options
 * such as trade size, time in force, stop loss, take profit, limit prices, trailing stops,
 * and target markets. The use of "dynamic_value" and "trade_option" types allows for
 * flexible chaining with other blocks, enhancing the modularity and interconnectivity
 * of the Blockly environment.
 *
 * Ensure that this file is loaded **after** the `json_base_generator.js` and any other
 * necessary Blockly setup files to maintain proper loading order and functionality.
 */
export function defineTradeOrderBlocks() {

    // Generate dropdown options based on available data
    const timeframeOptions = bt_data.intervals.map(interval => [interval, interval]);
    const exchangeOptions = window.UI.exchanges.connected_exchanges.map(exchange => [exchange, exchange]);
    const symbolOptions = bt_data.symbols.map(symbol => [symbol, symbol]);

    /**
     * trade_action
     * Executes a trade action (Buy/Sell), specifying the amount and optional trade options.
     */
    Blockly.defineBlocksWithJsonArray([
        {
            "type": "trade_action",
            "message0": "%1 amount %2 %3 (Options) %4",
            "args0": [
                {
                    "type": "field_dropdown",
                    "name": "trade_type",
                    "options": [
                        ["Buy", "buy"],
                        ["Sell", "sell"]
                    ],
                },
                {
                    "type": "input_value",
                    "name": "size",
                    "check": "dynamic_value",
                    "align": "RIGHT"
                },
                {
                    "type": "input_statement",
                    "name": "trade_options",
                    "check": "trade_option",
                    "align": "LEFT"
                },
                {
                    "type": "field_label",
                    "name": "dummy",
                    "text": ""
                }
            ],
            "previousStatement": null,
            "nextStatement": null,
            "colour": 230,
            "tooltip": "Execute a Buy or Sell trade with the specified size. Additional trade options can be configured.",
            "helpUrl": "https://example.com/docs/trade_action"
        }
    ]);

    /**
     * time_in_force
     * Sets the time in force for the order (GTC, FOK, IOC).
     */
    Blockly.defineBlocksWithJsonArray([{
        "type": "time_in_force",
        "message0": "Time in Force %1",
        "args0": [
            {
                "type": "field_dropdown",
                "name": "tif",
                "options": [
                    ["GTC (Good Till Canceled)", "gtc"],
                    ["FOK (Fill or Kill)", "fok"],
                    ["IOC (Immediate or Cancel)", "ioc"]
                ],
                "align": "RIGHT"
            }
        ],
        "previousStatement": "trade_option",
        "nextStatement": "trade_option",
        "colour": 230,
        "tooltip": "Select how long the order remains active:\n- GTC (Good Till Canceled): Remains active until filled or canceled.\n- FOK (Fill or Kill): Must be filled immediately in its entirety or canceled.\n- IOC (Immediate or Cancel): Partially filled orders are canceled if not filled immediately.",
        "helpUrl": "https://example.com/docs/time_in_force"
    }]);

    /**
     * stop_loss
     * Sets the Stop Loss parameter for a trade.
     */
    Blockly.defineBlocksWithJsonArray([
        {
            "type": "stop_loss",
            "message0": "Stop Loss %1",
            "args0": [
                {
                    "type": "input_value",
                    "name": "stop_loss_input",
                    "check": ["number", "dynamic_value"],
                    "align": "RIGHT"
                }
            ],
            "previousStatement": "trade_option",
            "nextStatement": "trade_option",
            "colour": 230,
            "tooltip": "Set the Stop Loss price to limit potential losses. If the market reaches this price, the position will be automatically closed.",
            "helpUrl": "https://example.com/docs/stop_loss"
        }
    ]);

    /**
     * trailing_stop
     * Sets a trailing stop to lock in profits as the price moves favorably.
     */
    Blockly.defineBlocksWithJsonArray([{
        "type": "trailing_stop",
        "message0": "Trailing Stop %1",
        "args0": [
            {
                "type": "input_value",
                "name": "trail_distance",
                "check": ["number", "dynamic_value"],
                "align": "RIGHT"
            }
        ],
        "previousStatement": "trade_option",
        "nextStatement": "trade_option",
        "colour": 230,
        "tooltip": "Set a Trailing Stop to automatically adjust the Stop Loss level as the market price moves favorably, helping to lock in profits while allowing for potential gains.",
        "helpUrl": "https://example.com/docs/trailing_stop"
    }]);

    /**
     * take_profit
     * Sets the Take Profit parameter for a trade.
     */
    Blockly.defineBlocksWithJsonArray([
        {
            "type": "take_profit",
            "message0": "Take Profit %1",
            "args0": [
                {
                    "type": "input_value",
                    "name": "take_profit_input",
                    "check": ["number", "dynamic_value"],
                    "align": "RIGHT"
                }
            ],
            "previousStatement": "trade_option",
            "nextStatement": "trade_option",
            "colour": 230,
            "tooltip": "Set the Take Profit price to secure profits. If the market reaches this price, the position will be automatically closed.",
            "helpUrl": "https://example.com/docs/take_profit"
        }
    ]);

    /**
     * limit
     * Sets the Price parameter for a trade order.
     * Accepts numerical value or dynamic value. If a single value is provided,
     * the limit order will execute at the specified price. If two values are provided,
     * the first value acts as a trigger price, and the second as the execution price.
     */
    Blockly.defineBlocksWithJsonArray([
        {
            "type": "limit",
            "message0": "Limit %1",
            "args0": [
                {
                    "type": "input_value",
                    "name": "limit_input",
                    "check": ["number", "dynamic_value"],
                    "align": "RIGHT"
                }
            ],
            "previousStatement": "trade_option",
            "nextStatement": "trade_option",
            "colour": 230,
            "tooltip": "Set the Limit price for the order. A single value sets a straightforward limit order. Providing two values sets a conditional limit order.",
            "helpUrl": "https://example.com/docs/limit"
        }
    ]);

    /**
     * trailing_limit
     * Sets a trailing limit to ensure a limit purchase as the price moves favorably.
     */
    Blockly.defineBlocksWithJsonArray([{
        "type": "trailing_limit",
        "message0": "Trailing Limit %1",
        "args0": [
            {
                "type": "input_value",
                "name": "trail_limit_distance",
                "check": ["number", "dynamic_value"],
                "align": "RIGHT"
            }
        ],
        "previousStatement": "trade_option",
        "nextStatement": "trade_option",
        "colour": 230,
        "tooltip": "Set a Trailing Limit to automatically adjust the Limit price as the market price moves favorably, ensuring optimal entry points while locking in potential gains.",
        "helpUrl": "https://example.com/docs/trailing_limit"
    }]);

    /**
     * target_market
     * Defines the target market for executing trades with specified Time Frame, Exchange, and Symbol.
     */
    Blockly.defineBlocksWithJsonArray([{
        "type": "target_market",
        "message0": "Target market: TF %1 Ex %2 Sym %3",
        "args0": [
            {
                "type": "field_dropdown",
                "name": "TF",
                "options": timeframeOptions,
                "align": "RIGHT"
            },
            {
                "type": "field_dropdown",
                "name": "EXC",
                "options": exchangeOptions,
                "align": "RIGHT"
            },
            {
                "type": "field_dropdown",
                "name": "SYM",
                "options": symbolOptions,
                "align": "RIGHT"
            }
        ],
        "previousStatement": "trade_option",
        "nextStatement": "trade_option",
        "colour": 230,
        "tooltip": "Specify the target market by selecting the Time Frame, Exchange, and Symbol for executing trades.",
        "helpUrl": "https://example.com/docs/target_market"
    }]);

    /**
     * name_order
     * Assign a custom name to the current order.
     */
    Blockly.defineBlocksWithJsonArray([{
        "type": "name_order",
        "message0": "Name Order %1",
        "args0": [
            {
                "type": "field_input",
                "name": "order_name",
                "text": "order_name",
                "spellcheck": true,
                "align": "RIGHT"
            }
        ],
        "previousStatement": "trade_option",
        "nextStatement": "trade_option",
        "colour": 230,
        "tooltip": "Assign a unique name to the order for easier tracking and identification in trade logs.",
        "helpUrl": "https://example.com/docs/name_order"
    }]);
};
