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

export type {{ instructionParsedType }}<
  TProgram extends string = typeof {{ programAddressConstant }},
  {% if hasAccounts %}
    TAccountMetas extends readonly IAccountMeta[] = readonly IAccountMeta[],
  {% endif %}
> = {
  programAddress: Address<TProgram>;
  {% if hasAccounts %}
    accounts: {
      {% for account in instruction.accounts %}
        {% if account.docs.length > 0 %}
          {{ macros.docblock(account.docs) }}
        {% endif %}
        {{ account.name | camelCase }}{{ '?' if account.isOptional }}: TAccountMetas[{{ loop.index0 }}]{{ ' | undefined' if account.isOptional }},
      {% endfor %}
    };
  {% endif %}
  {% if hasData %}
    data: {{ dataTypeFragment }};
  {% endif %}
};

export function {{ instructionParseFunction }}<
  TProgram extends string,
  {% if hasAccounts %}
    TAccountMetas extends readonly IAccountMeta[],
  {% endif %}
>(
  instruction: IInstruction<TProgram>
    {% if hasAccounts %}
      & IInstructionWithAccounts<TAccountMetas>
    {% endif %}
    {% if hasData %}
      & IInstructionWithData<Uint8Array>
    {% endif %}
): {{ instructionParsedType }}<TProgram {{ ', TAccountMetas' if hasAccounts }}> {
  {% if hasAccounts %}
    if (instruction.accounts.length < {{ minimumNumberOfAccounts }}) {
      // TODO: Coded error.
      throw new Error('Not enough accounts');
    }
    let accountIndex = 0;
    const getNextAccount = () => {
      const accountMeta = instruction.accounts![accountIndex]!;
      accountIndex += 1;
      return accountMeta;
    }
    {% if hasOptionalAccounts and instruction.optionalAccountStrategy === 'programId' %}
      const getNextOptionalAccount = () => {
        const accountMeta = getNextAccount();
        return accountMeta.address === {{ programAddressConstant }} ? undefined : accountMeta;
      };
    {% elif hasOptionalAccounts and instruction.optionalAccountStrategy === 'omitted' %}
      let optionalAccountsRemaining = instruction.accounts.length - {{ minimumNumberOfAccounts }};
      const getNextOptionalAccount = () => {
        if (optionalAccountsRemaining === 0) return undefined;
        optionalAccountsRemaining -= 1;
        return getNextAccount();
      };
    {% endif %}
  {% endif %}
  return {
    programAddress: instruction.programAddress,
    {% if hasAccounts %}
      accounts: {
        {% for account in instruction.accounts %}
          {% if account.isOptional %}
            {{ account.name | camelCase }}: getNextOptionalAccount(),
          {% else %}
            {{ account.name | camelCase }}: getNextAccount(),
          {% endif %}
        {% endfor %}
      },
    {% endif %}
    {% if hasData %}
      data: {{ decoderFunction }}.decode(instruction.data),
    {% endif %}
  };
}
