import { PublicKey } from "@solana/web3.js";
import { BN, Program } from "@coral-xyz/anchor";
import { BasketsProgram } from "../idl/types";


export const WITHDRAW_STATE_SIZE = 8155;

export interface WithdrawState {
    ownAddress: PublicKey,
    withdrawStateSeed: number[],
    basket: PublicKey,
    owner: PublicKey,

    numTokens: number,
    compositionMints: PublicKey[],
    compositionAmounts: BN[],

    rebalance: number,
    destinationMint: PublicKey,
    destinationAmount: BN,
}

export interface ParsedWithdrawState {
    ownAddress: string,
    withdrawStateSeed: number[],
    basket: string,
    owner: string,

    numTokens: number,
    compositionMints: string[],
    compositionAmounts: number[],

    rebalance: number,
    destinationMint: string,
    destinationAmount: number,
}

export async function fetchWithdrawState(
    program: Program<BasketsProgram>,
    basket: PublicKey
): Promise<WithdrawState> {
    return await program.account.withdrawStateV200.fetch(basket);
}

export function parseWithdrawState(
    withdrawState: WithdrawState
): ParsedWithdrawState {
    return {
        ownAddress: withdrawState.ownAddress.toBase58(),
        withdrawStateSeed: withdrawState.withdrawStateSeed,
        basket: withdrawState.basket.toBase58(),
        owner: withdrawState.owner.toBase58(),
        numTokens: withdrawState.numTokens,
        compositionMints: withdrawState.compositionMints.map(mint => mint.toBase58()).slice(0, withdrawState.numTokens),
        compositionAmounts: withdrawState.compositionAmounts.map(amount => parseInt(amount.toString())).slice(0, withdrawState.numTokens),
        rebalance: withdrawState.rebalance,
        destinationMint: withdrawState.destinationMint.toBase58(),
        destinationAmount: parseInt(withdrawState.destinationAmount.toString()),
    }
}
