{% extends "layout.njk" %}
{% import "macros.njk" as macros %}

{% block main %}

{{ imports }}

{{ macros.docblock(account.docs) }}
{{ typeManifest.type }}

{% for nestedStruct in typeManifest.nestedStructs %}
{{ nestedStruct }}
{% endfor %}

{{ discriminatorConstants }}

impl {{ account.name | pascalCase }} {
  {% if account.size != null %}
    pub const LEN: usize = {{ account.size }};
  {% endif %}

  {% if constantSeeds.length > 0 %}
    {% set index = 0 %}
    /// Prefix values used to generate a PDA for this account.
    ///
    /// Values are positional and appear in the following order:
    ///
    {% for seed in seeds %}
      {% if seed.kind === 'constantPdaSeedNode' and seed.value.kind === 'programIdValueNode' %}
        ///   {{ loop.index0 }}. `crate::{{ program.name | snakeCase | upper }}_ID`
      {% elif seed.kind === 'constantPdaSeedNode' %}
        ///   {{ loop.index0 }}. `{{ account.name | pascalCase }}::PREFIX{{ '.' + index if constantSeeds.length > 1 }}`
        {% set index = index + 1 %}
      {% else %}
        ///   {{ loop.index0 }}. {{ seed.name | snakeCase }} (`{{ seed.typeManifest.type }}`)
      {% endif %}
    {% endfor %}
    {% if constantSeeds.length > 1 %}
      pub const PREFIX: (
      {% for seed in constantSeeds %}
        &'static [u8],
      {% endfor %}
      ) = (
      {% for seed in constantSeeds %}
        {{ seed.valueManifest.render }}.as_bytes(),
      {% endfor %}
      );
    {% elif constantSeeds.length === 1 %}
      pub const PREFIX: &'static [u8] = {{ constantSeeds[0].valueManifest.render }}.as_bytes();
    {% endif %}
  {% endif %}

  {% if pda %}
    pub fn create_pda(
      {% if hasVariableSeeds %}
          {% for seed in seeds %}
            {% if seed.kind === 'variablePdaSeedNode' %}
              {{ seed.name | snakeCase }}: {{ seed.typeManifest.type }},
            {% endif %}
          {% endfor %}
      {% endif %}
      bump: u8,
    ) -> Result<solana_pubkey::Pubkey, solana_pubkey::PubkeyError> {
      solana_pubkey::Pubkey::create_program_address(
        &[
          {% for seed in seeds %}
            {% if seed.kind === 'constantPdaSeedNode' and seed.value.kind === 'programIdValueNode' %}
              crate::{{ program.name | snakeCase | upper }}_ID.as_ref(),
            {% elif seed.kind === 'constantPdaSeedNode' %}
              {{ seed.valueManifest.render }}.as_bytes(),
            {% elif seed.kind == 'variablePdaSeedNode' and seed.resolvedType.kind == 'publicKeyTypeNode' %}
              {{ seed.name | snakeCase }}.as_ref(),
            {% elif seed.kind == 'variablePdaSeedNode' and seed.resolvedType.kind == 'bytesTypeNode' %}
              &{{ seed.name | snakeCase }},
            {% else %}
              {{ seed.name | snakeCase }}.to_string().as_ref(),
            {% endif %}
          {% endfor %}
          &[bump],
        ],
        &crate::{{ program.name | snakeCase | upper }}_ID,
      )
    }

    pub fn find_pda(
    {% if hasVariableSeeds %}
        {% for seed in seeds %}
          {% if seed.kind == 'variablePdaSeedNode' and seed.resolvedType.kind == 'publicKeyTypeNode' %}
            {{ seed.name | snakeCase }}: &{{ seed.typeManifest.type }},
          {% elif seed.kind === 'variablePdaSeedNode' %}
            {{ seed.name | snakeCase }}: {{ seed.typeManifest.type }},
          {% endif %}
        {% endfor %}
    {% endif %}
    ) -> (solana_pubkey::Pubkey, u8) {
      solana_pubkey::Pubkey::find_program_address(
        &[
          {% for seed in seeds %}
            {% if seed.kind === 'constantPdaSeedNode' and seed.value.kind === 'programIdValueNode' %}
              crate::{{ program.name | snakeCase | upper }}_ID.as_ref(),
            {% elif seed.kind === 'constantPdaSeedNode' %}
              {{ seed.valueManifest.render }}.as_bytes(),
            {% elif seed.kind == 'variablePdaSeedNode' and seed.resolvedType.kind == 'publicKeyTypeNode' %}
              {{ seed.name | snakeCase }}.as_ref(),
            {% elif seed.kind == 'variablePdaSeedNode' and seed.resolvedType.kind == 'bytesTypeNode' %}
              &{{ seed.name | snakeCase }},
            {% else %}
              {{ seed.name | snakeCase }}.to_string().as_ref(),
            {% endif %}
          {% endfor %}
        ],
        &crate::{{ program.name | snakeCase | upper }}_ID,
      )
    }
  {% endif %}

  #[inline(always)]
  pub fn from_bytes(data: &[u8]) -> Result<Self, std::io::Error> {
    let mut data = data;
    Self::deserialize(&mut data)
  }
}

impl<'a> TryFrom<&solana_account_info::AccountInfo<'a>> for {{ account.name | pascalCase }} {
  type Error = std::io::Error;

  fn try_from(account_info: &solana_account_info::AccountInfo<'a>) -> Result<Self, Self::Error> {
      let mut data: &[u8] = &(*account_info.data).borrow();
      Self::deserialize(&mut data)
  }
}

#[cfg(feature = "fetch")]
pub fn fetch_{{ account.name | snakeCase }}(
  rpc: &solana_client::rpc_client::RpcClient,
  address: &solana_pubkey::Pubkey,
) -> Result<crate::shared::DecodedAccount<{{ account.name | pascalCase }}>, std::io::Error> {
  let accounts = fetch_all_{{ account.name | snakeCase }}(rpc, &[*address])?;
  Ok(accounts[0].clone())
}

#[cfg(feature = "fetch")]
pub fn fetch_all_{{ account.name | snakeCase }}(
  rpc: &solana_client::rpc_client::RpcClient,
  addresses: &[solana_pubkey::Pubkey],
) -> Result<Vec<crate::shared::DecodedAccount<{{ account.name | pascalCase }}>>, std::io::Error> {
    let accounts = rpc.get_multiple_accounts(addresses)
      .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e.to_string()))?;
    let mut decoded_accounts: Vec<crate::shared::DecodedAccount<{{ account.name | pascalCase }}>> = Vec::new();
    for i in 0..addresses.len() {
      let address = addresses[i];
      let account = accounts[i].as_ref()
        .ok_or(std::io::Error::new(std::io::ErrorKind::Other, format!("Account not found: {}", address)))?;
      let data = {{ account.name | pascalCase }}::from_bytes(&account.data)?;
      decoded_accounts.push(crate::shared::DecodedAccount { address, account: account.clone(), data });
    }
    Ok(decoded_accounts)
}

#[cfg(feature = "fetch")]
pub fn fetch_maybe_{{ account.name | snakeCase }}(
  rpc: &solana_client::rpc_client::RpcClient,
  address: &solana_pubkey::Pubkey,
) -> Result<crate::shared::MaybeAccount<{{ account.name | pascalCase }}>, std::io::Error> {
    let accounts = fetch_all_maybe_{{ account.name | snakeCase }}(rpc, &[*address])?;
    Ok(accounts[0].clone())
}

#[cfg(feature = "fetch")]
pub fn fetch_all_maybe_{{ account.name | snakeCase }}(
  rpc: &solana_client::rpc_client::RpcClient,
  addresses: &[solana_pubkey::Pubkey],
) -> Result<Vec<crate::shared::MaybeAccount<{{ account.name | pascalCase }}>>, std::io::Error> {
    let accounts = rpc.get_multiple_accounts(addresses)
      .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e.to_string()))?;
    let mut decoded_accounts: Vec<crate::shared::MaybeAccount<{{ account.name | pascalCase }}>> = Vec::new();
    for i in 0..addresses.len() {
      let address = addresses[i];
      if let Some(account) = accounts[i].as_ref() {
        let data = {{ account.name | pascalCase }}::from_bytes(&account.data)?;
        decoded_accounts.push(crate::shared::MaybeAccount::Exists(crate::shared::DecodedAccount { address, account: account.clone(), data }));
      } else {
        decoded_accounts.push(crate::shared::MaybeAccount::NotFound(address));
      }
    }
  Ok(decoded_accounts)
}

{% if anchorTraits %}
  #[cfg(feature = "anchor")]
  impl anchor_lang::AccountDeserialize for {{ account.name | pascalCase }} {
      fn try_deserialize_unchecked(buf: &mut &[u8]) -> anchor_lang::Result<Self> {
        Ok(Self::deserialize(buf)?)
      }
  }

  #[cfg(feature = "anchor")]
  impl anchor_lang::AccountSerialize for {{ account.name | pascalCase }} {}

  #[cfg(feature = "anchor")]
  impl anchor_lang::Owner for {{ account.name | pascalCase }} {
      fn owner() -> Pubkey {
        crate::{{ program.name | snakeCase | upper }}_ID
      }
  }

  #[cfg(feature = "anchor-idl-build")]
  impl anchor_lang::IdlBuild for {{ account.name | pascalCase }} {}

  {#
    This is not used for the IDL generation since default `IdlBuild` impl doesn't include
    the type in the IDL but it stil needs to be added in order to make compilation work.
  #}
  #[cfg(feature = "anchor-idl-build")]
  impl anchor_lang::Discriminator for {{ account.name | pascalCase }} {
    const DISCRIMINATOR: &[u8] = &[0; 8];
  }
{% endif %}

{% endblock %}
