#!/usr/bin/env python3

import argparse
import os
import os.path
import sys

from decimal import Decimal
from solana.publickey import PublicKey

sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
import mango  # nopep8

parser = argparse.ArgumentParser(description="Shows all orders on a market.")
mango.ContextBuilder.add_command_line_parameters(parser)
mango.Wallet.add_command_line_parameters(parser)
parser.add_argument(
    "--market", type=str, required=True, help="market symbol to buy (e.g. ETH/USDC)"
)
parser.add_argument(
    "--quantity", type=Decimal, required=True, help="quantity to BUY or SELL"
)
parser.add_argument(
    "--price", type=Decimal, required=True, help="price to BUY or SELL at"
)
parser.add_argument(
    "--side",
    type=mango.Side,
    required=True,
    choices=list(mango.Side),
    help="side: BUY or SELL",
)
parser.add_argument(
    "--order-type",
    type=mango.OrderType,
    required=True,
    choices=list(mango.OrderType),
    help="Order type: LIMIT, IOC or POST_ONLY",
)
parser.add_argument(
    "--account-address",
    type=PublicKey,
    help="address of the specific account to use, if more than one available",
)
parser.add_argument(
    "--wait",
    action="store_true",
    default=False,
    help="wait until the transactions are confirmed",
)
parser.add_argument(
    "--match-limit",
    type=int,
    help="maximum number of orders this order can match with on the orderbook",
)
parser.add_argument(
    "--expire-seconds",
    type=Decimal,
    help="maximum number of seconds from now for which the order will be valid on the orderbook",
)
parser.add_argument(
    "--dry-run",
    action="store_true",
    default=False,
    help="runs as read-only and does not perform any transactions",
)
args: argparse.Namespace = mango.parse_args(parser)

with mango.ContextBuilder.from_command_line_parameters(args) as context:
    wallet = mango.Wallet.from_command_line_parameters_or_raise(args)
    group = mango.Group.load(context, context.group_address)
    account = mango.Account.load_for_owner_by_address(
        context, wallet.address, group, args.account_address
    )

    market_operations = mango.operations(
        context, wallet, account, args.market, args.dry_run
    )
    order: mango.Order = mango.Order.from_values(
        args.side, args.price, args.quantity, args.order_type
    )

    if args.match_limit is not None:
        order = order.with_update(match_limit=args.match_limit)

    if args.expire_seconds is not None:
        expiration = mango.Order.build_absolute_expiration(args.expire_seconds)
        order = order.with_update(expiration=expiration)

    signatures = market_operations.place_order(order)

    if args.wait:
        mango.output("Waiting on transaction signatures:")
        mango.output(mango.indent_collection_as_str(signatures, 1))
        results = mango.WebSocketTransactionMonitor.wait_for_all(
            context.client.cluster_ws_url, signatures
        )
        mango.output("Transaction results:")
        mango.output(mango.indent_collection_as_str(results, 1))
    else:
        mango.output("Transaction signatures:")
        mango.output(mango.indent_collection_as_str(signatures, 1))
