use anchor_lang::{Discriminator, Owner, ZeroCopy};
use bytemuck::{Pod, Zeroable};
use solana_program::pubkey::Pubkey;
use crate::SWITCHBOARD_ATTESTATION_PROGRAM_ID;
use anchor_lang::zero_copy;
use crate::STATE_SEED;
use crate::cfg_client;

#[zero_copy(unsafe)]
#[repr(packed)]
#[derive(Debug)]
pub struct State {
    pub bump: u8,
    pub authority: Pubkey,
    pub guardian_queue: Pubkey,
    pub min_quote_verify_votes: u64,
    pub _ebuf: [u8; 2048],
}

impl anchor_lang::AccountDeserialize for State {
    fn try_deserialize(buf: &mut &[u8]) -> anchor_lang::Result<Self> {
        if buf.len() < State::discriminator().len() {
            return Err(anchor_lang::error::ErrorCode::AccountDiscriminatorNotFound.into());
        }
        let given_disc = &buf[..8];
        if State::discriminator() != given_disc {
            return Err(
                anchor_lang::error::Error::from(anchor_lang::error::AnchorError {
                    error_name: anchor_lang::error::ErrorCode::AccountDiscriminatorMismatch.name(),
                    error_code_number: anchor_lang::error::ErrorCode::AccountDiscriminatorMismatch
                        .into(),
                    error_msg: anchor_lang::error::ErrorCode::AccountDiscriminatorMismatch
                        .to_string(),
                    error_origin: Some(anchor_lang::error::ErrorOrigin::Source(
                        anchor_lang::error::Source {
                            filename: "programs/attestation_program/src/lib.rs",
                            line: 1u32,
                        },
                    )),
                    compared_values: None,
                })
                .with_account_name("State"),
            );
        }
        Self::try_deserialize_unchecked(buf)
    }

    fn try_deserialize_unchecked(buf: &mut &[u8]) -> anchor_lang::Result<Self> {
        let data: &[u8] = &buf[8..];
        bytemuck::try_from_bytes(data)
            .map(|r: &Self| *r)
            .map_err(|_| anchor_lang::error::ErrorCode::AccountDidNotDeserialize.into())
    }
}

unsafe impl Pod for State {}
unsafe impl Zeroable for State {}

impl Discriminator for State {
    const DISCRIMINATOR: [u8; 8] = [216, 146, 107, 94, 104, 75, 182, 177];
}

impl Owner for State {
    fn owner() -> Pubkey {
        *SWITCHBOARD_ATTESTATION_PROGRAM_ID
    }
}

impl ZeroCopy for State {}

impl State {
    pub fn size() -> usize {
        8 + std::mem::size_of::<State>()
    }

    pub fn get_pda() -> Pubkey {
        let (pda_key, _) =
            Pubkey::find_program_address(&[STATE_SEED], &*SWITCHBOARD_ATTESTATION_PROGRAM_ID);
        pda_key
    }

    pub fn get_program_pda(program_id: Option<Pubkey>) -> Pubkey {
        let (pda_key, _) = Pubkey::find_program_address(
            &[STATE_SEED],
            &program_id.unwrap_or(*SWITCHBOARD_ATTESTATION_PROGRAM_ID),
        );
        pda_key
    }

    cfg_client! {
        pub async fn fetch_async(
            client: &solana_client::nonblocking::rpc_client::RpcClient,
        ) -> std::result::Result<Self, crate::OnDemandError> {
            let pubkey = State::get_pda();
            crate::client::fetch_zerocopy_account_async(client, pubkey).await
        }
    }
}
