#!/usr/bin/env python3

import argparse
import os
import os.path
import sys

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="Delegate operational authority of a Mango account to another account."
)
mango.ContextBuilder.add_command_line_parameters(parser)
mango.Wallet.add_command_line_parameters(parser)
parser.add_argument(
    "--account-address",
    type=PublicKey,
    required=True,
    help="address of the Mango account to delegate",
)
parser.add_argument(
    "--delegate-address",
    type=PublicKey,
    required=False,
    help="address of the account to which to delegate operational control of the Mango account",
)
parser.add_argument(
    "--revoke",
    action="store_true",
    default=False,
    help="revoke any previous account delegation",
)
parser.add_argument(
    "--wait",
    action="store_true",
    default=False,
    help="wait until the transactions are confirmed",
)
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 = mango.Account.load(context, args.account_address, group)
    if account.owner != wallet.address:
        raise Exception(
            f"Account {account.address} is not owned by current wallet {wallet.address}."
        )

    all_instructions: mango.CombinableInstructions = (
        mango.CombinableInstructions.from_signers([wallet.keypair])
    )
    if args.revoke:
        unset_delegate_instructions = (
            mango.build_mango_unset_account_delegate_instructions(
                context, wallet, group, account
            )
        )
        all_instructions += unset_delegate_instructions
    else:
        if args.delegate_address is None:
            raise Exception("No delegate address specified")

        set_delegate_instructions = mango.build_mango_set_account_delegate_instructions(
            context, wallet, group, account, args.delegate_address
        )
        all_instructions += set_delegate_instructions

    signatures = all_instructions.execute(context)

    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))
