use super::VmApiImpl;
use elrond_wasm::{
    api::{Handle, LogApi, LogApiImpl},
    types::ArgBuffer,
};

extern "C" {
    fn writeLog(pointer: *const u8, length: i32, topicPtr: *const u8, numTopics: i32);

    fn writeEventLog(
        numTopics: i32,
        topicLengthsOffset: *const u8,
        topicOffset: *const u8,
        dataOffset: *const u8,
        dataLength: i32,
    );

    #[cfg(not(feature = "unmanaged-ei"))]
    fn managedWriteLog(topicsHandle: i32, dataHandle: i32);
}

const LEGACY_TOPIC_LENGTH: usize = 32;

impl LogApi for VmApiImpl {
    type LogApiImpl = VmApiImpl;

    #[inline]
    fn log_api_impl() -> Self::LogApiImpl {
        VmApiImpl {}
    }
}

/// Interface to only be used by code generated by the macros.
/// The smart contract code doesn't have access to these methods directly.
impl LogApiImpl for VmApiImpl {
    fn write_event_log(&self, topics_buffer: &ArgBuffer, data: &[u8]) {
        unsafe {
            writeEventLog(
                topics_buffer.num_args() as i32,
                topics_buffer.arg_lengths_bytes_ptr(),
                topics_buffer.arg_data_ptr(),
                data.as_ptr(),
                data.len() as i32,
            );
        }
    }

    fn write_legacy_log(&self, topics: &[[u8; 32]], data: &[u8]) {
        let mut topics_raw = [0u8; LEGACY_TOPIC_LENGTH * 10]; // hopefully we never have more than 10 topics
        for i in 0..topics.len() {
            topics_raw[LEGACY_TOPIC_LENGTH * i..LEGACY_TOPIC_LENGTH * (i + 1)]
                .copy_from_slice(&topics[i]);
        }
        unsafe {
            writeLog(
                data.as_ptr(),
                data.len() as i32,
                topics_raw.as_ptr(),
                topics.len() as i32,
            );
        }
    }

    #[cfg(feature = "unmanaged-ei")]
    fn managed_write_log(&self, topics_handle: Handle, data_handle: Handle) {
        use elrond_wasm::types::{
            managed_vec_of_buffers_to_arg_buffer, ManagedBuffer, ManagedType, ManagedVec,
        };
        let topics = ManagedVec::<Self, ManagedBuffer<Self>>::from_raw_handle(topics_handle);
        let topics_arg_buffer = managed_vec_of_buffers_to_arg_buffer(topics);
        let data = ManagedBuffer::<Self>::from_raw_handle(data_handle);
        self.write_event_log(&topics_arg_buffer, data.to_boxed_bytes().as_slice());
    }

    #[cfg(not(feature = "unmanaged-ei"))]
    fn managed_write_log(&self, topics_handle: Handle, data_handle: Handle) {
        unsafe {
            managedWriteLog(topics_handle, data_handle);
        }
    }
}
