use super::tunnel::*;
use babalcore::*;
use gdnative::prelude::*;

pub struct TunnelWrapper<'a> {
    obj: RefInstance<'a, Tunnel, Shared>,
}

impl TunnelWrapper<'_> {
    pub fn new<'a>(instance: RefInstance<'a, Tunnel, Shared>) -> TunnelWrapper<'a> {
        TunnelWrapper::<'a> { obj: instance }
    }

    pub fn from_variant<'a>(variant: &'a Variant) -> Result<TunnelWrapper<'a>, FromVariantError> {
        match variant.try_to_object_with_error::<Spatial>() {
            Ok(obj) => {
                let obj = unsafe { obj.assume_safe() };
                if let Some(tun) = obj.cast_instance::<Tunnel>() {
                    Ok(Self::new(tun))
                } else {
                    Err(FromVariantError::CannotCast {
                        class: format_type_of(&obj),
                        to: "Tunnel",
                    })
                }
            }
            Err(e) => Err(e),
        }
    }
}

impl LevelQuery for TunnelWrapper<'_> {
    fn width(&self) -> usize {
        match self.obj.map(|x, o| x.width(&o)) {
            Ok(v) => v,
            Err(e) => {
                godot_print!("unable to get tunnel width: {}", e);
                0
            }
        }
    }

    fn len(&self) -> usize {
        match self.obj.map(|x, o| x.len(&o)) {
            Ok(v) => v,
            Err(e) => {
                godot_print!("unable to get tunnel len: {}", e);
                0
            }
        }
    }

    fn first(&self) -> isize {
        match self.obj.map(|x, o| x.first(&o)) {
            Ok(v) => v,
            Err(e) => {
                godot_print!("unable to get tunnel first row: {}", e);
                0
            }
        }
    }

    fn last(&self) -> isize {
        match self.obj.map(|x, o| x.last(&o)) {
            Ok(v) => v,
            Err(e) => {
                godot_print!("unable to get tunnel last row: {}", e);
                0
            }
        }
    }

    fn item(&self, col: isize, row: isize, boost: bool) -> i64 {
        match self.obj.map(|x, o| x.item(&o, col, row, boost)) {
            Ok(v) => v,
            Err(e) => {
                godot_print!("unable to get tunnel item: {}", e);
                0
            }
        }
    }

    fn find_start_spot(&self, col: isize, row: isize) -> Option<(isize, isize)> {
        match self.obj.map(|x, o| x.find_start_spot(&o, col, row)) {
            Ok(v) => v,
            Err(e) => {
                godot_print!("unable find tunnel start spot: {}", e);
                None
            }
        }
    }

    fn skill(&self) -> Skill {
        match self.obj.map(|x, o| x.skill(&o)) {
            Ok(v) => Skill::from_str(v.to_string().as_str()),
            Err(e) => {
                godot_print!("unable to get skill for tunnel: {}", e);
                Skill::default()
            }
        }
    }
}
