use crate::{heap_drop, heap_move, heap_move_nonnull, heap_remove, ByteSlice};
use servicepoint::{CharGrid, CharGridCommand, Grid, Origin, Packet};
use std::ptr::NonNull;

/// Creates a new [CharGrid] with the specified dimensions.
///
/// returns: [CharGrid] initialized to 0.
///
/// # Examples
///
/// ```C
/// CharGrid grid = sp_char_grid_new(4, 3);
/// sp_char_grid_fill(grid, '?');
/// sp_char_grid_set(grid, 0, 0, '!');
/// sp_char_grid_free(grid);
/// ```
#[no_mangle]
pub unsafe extern "C" fn sp_char_grid_new(
    width: usize,
    height: usize,
) -> NonNull<CharGrid> {
    heap_move_nonnull(CharGrid::new(width, height))
}

/// Loads a [CharGrid] with the specified dimensions from the provided data.
///
/// returns: new CharGrid or NULL in case of an error
#[no_mangle]
pub unsafe extern "C" fn sp_char_grid_load(
    width: usize,
    height: usize,
    data: ByteSlice,
) -> *mut CharGrid {
    let data = unsafe { data.as_slice() };
    if let Ok(grid) = CharGrid::load_utf8(width, height, data.to_vec()) {
        heap_move(grid)
    } else {
        std::ptr::null_mut()
    }
}

/// Clones a [CharGrid].
#[no_mangle]
pub unsafe extern "C" fn sp_char_grid_clone(
    char_grid: NonNull<CharGrid>,
) -> NonNull<CharGrid> {
    heap_move_nonnull(unsafe { char_grid.as_ref().clone() })
}

/// Deallocates a [CharGrid].
#[no_mangle]
pub unsafe extern "C" fn sp_char_grid_free(char_grid: NonNull<CharGrid>) {
    unsafe { heap_drop(char_grid) }
}

/// Returns the current value at the specified position.
///
/// # Arguments
///
/// - `char_grid`: instance to read from
/// - `x` and `y`: position of the cell to read
///
/// # Panics
///
/// - when accessing `x` or `y` out of bounds
#[no_mangle]
pub unsafe extern "C" fn sp_char_grid_get(
    char_grid: NonNull<CharGrid>,
    x: usize,
    y: usize,
) -> u32 {
    unsafe { char_grid.as_ref().get(x, y) as u32 }
}

/// Sets the value of the specified position in the [CharGrid].
///
/// # Arguments
///
/// - `char_grid`: instance to write to
/// - `x` and `y`: position of the cell
/// - `value`: the value to write to the cell
///
/// returns: old value of the cell
///
/// # Panics
///
/// - when accessing `x` or `y` out of bounds
#[no_mangle]
pub unsafe extern "C" fn sp_char_grid_set(
    char_grid: NonNull<CharGrid>,
    x: usize,
    y: usize,
    value: u32,
) {
    unsafe { (*char_grid.as_ptr()).set(x, y, char::from_u32(value).unwrap()) };
}

/// Sets the value of all cells in the [CharGrid].
///
/// # Arguments
///
/// - `char_grid`: instance to write to
/// - `value`: the value to set all cells to
#[no_mangle]
pub unsafe extern "C" fn sp_char_grid_fill(
    char_grid: NonNull<CharGrid>,
    value: u32,
) {
    unsafe { (*char_grid.as_ptr()).fill(char::from_u32(value).unwrap()) };
}

/// Gets the width of the [CharGrid] instance.
///
/// # Arguments
///
/// - `char_grid`: instance to read from
#[no_mangle]
pub unsafe extern "C" fn sp_char_grid_width(
    char_grid: NonNull<CharGrid>,
) -> usize {
    unsafe { char_grid.as_ref().width() }
}

/// Gets the height of the [CharGrid] instance.
///
/// # Arguments
///
/// - `char_grid`: instance to read from
#[no_mangle]
pub unsafe extern "C" fn sp_char_grid_height(
    char_grid: NonNull<CharGrid>,
) -> usize {
    unsafe { char_grid.as_ref().height() }
}

/// Creates a [CharGridCommand] and immediately turns that into a [Packet].
///
/// The provided [CharGrid] gets consumed.
///
/// Returns NULL in case of an error.
#[no_mangle]
pub unsafe extern "C" fn sp_char_grid_into_packet(
    grid: NonNull<CharGrid>,
    x: usize,
    y: usize,
) -> *mut Packet {
    let grid = unsafe { heap_remove(grid) };
    match Packet::try_from(CharGridCommand {
        grid,
        origin: Origin::new(x, y),
    }) {
        Ok(packet) => heap_move(packet),
        Err(_) => std::ptr::null_mut(),
    }
}