use core::sync::atomic::{AtomicBool, Ordering};
use core::ops::{Deref, DerefMut};

use number_traits::Float;
use specs::{VecStorage, Component};

use super::InnerTransform3D;


pub struct LocalTransform3D<T: 'static + Sync + Send + Copy + Float> {
    wrapped: InnerTransform3D<T>,
    dirty: AtomicBool,
}


impl<T: 'static + Sync + Send + Copy + Float> Component for LocalTransform3D<T> {
    type Storage = VecStorage<Self>;
}


impl<T: 'static + Sync + Send + Copy + Float> Default for LocalTransform3D<T> {

    #[inline(always)]
    fn default() -> Self {
        LocalTransform3D {
            wrapped: InnerTransform3D::default(),
            dirty: AtomicBool::new(true),
        }
    }
}


impl<T: 'static + Sync + Send + Copy + Float> Deref for LocalTransform3D<T> {
    type Target = InnerTransform3D<T>;

    #[inline(always)]
    fn deref(&self) -> &Self::Target {
        &self.wrapped
    }
}


impl<T: 'static + Sync + Send + Copy + Float> DerefMut for LocalTransform3D<T> {

    #[inline]
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.flag(true);
        &mut self.wrapped
    }
}


impl<T: 'static + Sync + Send + Copy + Float> LocalTransform3D<T> {

    #[inline(always)]
    pub fn new() -> Self {
        Self::default()
    }

    #[inline(always)]
    pub fn flag(&self, dirty: bool) {
        self.dirty.store(dirty, Ordering::SeqCst)
    }

    #[inline(always)]
    pub fn is_dirty(&self) -> bool {
        self.dirty.load(Ordering::SeqCst)
    }

    #[inline(always)]
    pub fn matrix(&self) -> [T; 16] {
        self.wrapped.matrix()
    }
}
