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

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

use super::InnerTransform2D;


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


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


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

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


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

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


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

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


impl<T: 'static + Sync + Send + Copy + Float> LocalTransform2D<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; 6] {
        self.wrapped.matrix()
    }
}
