use multiversx_chain_vm_executor::VMHooksEarlyExit;
use num_bigint::{BigInt, BigUint};

use crate::{host::vm_hooks::VMHooksContext, types::RawHandle};

use super::VMHooksHandler;

/// Interface to only be used by code generated by the macros.
/// The smart contract code doesn't have access to these methods directly.
impl<C: VMHooksContext> VMHooksHandler<C> {
    pub fn finish_slice_u8(&mut self, slice: &[u8]) -> Result<(), VMHooksEarlyExit> {
        let mut v = vec![0u8; slice.len()];
        v.copy_from_slice(slice);
        let mut tx_result = self.context.result_lock();
        tx_result.result_values.push(v);

        Ok(())
    }

    pub fn finish_big_int_raw(&mut self, handle: RawHandle) -> Result<(), VMHooksEarlyExit> {
        let bi_bytes = self.bi_get_signed_bytes(handle)?;
        let mut tx_result = self.context.result_lock();

        tx_result.result_values.push(bi_bytes);

        Ok(())
    }

    pub fn finish_big_uint_raw(&mut self, handle: RawHandle) -> Result<(), VMHooksEarlyExit> {
        let bu_bytes = self.bi_get_unsigned_bytes(handle)?;
        let mut tx_result = self.context.result_lock();
        tx_result.result_values.push(bu_bytes);

        Ok(())
    }

    pub fn finish_managed_buffer_raw(&mut self, handle: RawHandle) -> Result<(), VMHooksEarlyExit> {
        self.use_gas(
            self.gas_schedule()
                .managed_buffer_api_cost
                .m_buffer_get_bytes,
        )?;

        let bytes = self.context.m_types_lock().mb_get_owned(handle);
        self.finish_slice_u8(&bytes)
    }

    pub fn finish_i64(&mut self, value: i64) -> Result<(), VMHooksEarlyExit> {
        if value == 0 {
            self.finish_slice_u8(&[])
        } else {
            self.finish_slice_u8(BigInt::from(value).to_signed_bytes_be().as_slice())
        }
    }

    pub fn finish_u64(&mut self, value: u64) -> Result<(), VMHooksEarlyExit> {
        if value == 0 {
            self.finish_slice_u8(&[])
        } else {
            self.finish_slice_u8(BigUint::from(value).to_bytes_be().as_slice())
        }
    }
}
