#!/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")
args: argparse.Namespace = mango.parse_args(parser)

context = mango.ContextBuilder.from_command_line_parameters(args)

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_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_set_account_delegate_instructions(
        context, wallet, group, account, args.delegate_address)
    all_instructions += set_delegate_instructions

transaction_ids = all_instructions.execute(context)
mango.output(f"Transaction IDs: {transaction_ids}")
