#!/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 entropy  # nopep8

parser = argparse.ArgumentParser(
    description="Delegate operational authority of a Entropy account to another account."
)
entropy.ContextBuilder.add_command_line_parameters(parser)
entropy.Wallet.add_command_line_parameters(parser)
parser.add_argument(
    "--account-address",
    type=PublicKey,
    required=True,
    help="address of the Entropy 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 Entropy 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 = entropy.parse_args(parser)

with entropy.ContextBuilder.from_command_line_parameters(args) as context:
    wallet = entropy.Wallet.from_command_line_parameters_or_raise(args)

    group = entropy.Group.load(context, context.group_address)
    account: entropy.Account = entropy.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: entropy.CombinableInstructions = (
        entropy.CombinableInstructions.from_signers([wallet.keypair])
    )
    if args.revoke:
        unset_delegate_instructions = (
            entropy.build_entropy_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 = (
            entropy.build_entropy_set_account_delegate_instructions(
                context, wallet, group, account, args.delegate_address
            )
        )
        all_instructions += set_delegate_instructions

    signatures = all_instructions.execute(context)

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