use {Line, Plane, is_zero};
use euclid::default::Point2D;
use euclid::{Transform3D, Point3D, Vector3D, Rect};
use euclid::approxeq::ApproxEq;
use euclid::Trig;
use num_traits::{Float, One, Zero};
use std::{fmt, iter, mem, ops};
pub struct LineProjection<T> {
    
    pub markers: [T; 4],
}
impl<T> LineProjection<T> where
    T : Copy + PartialOrd + ops::Sub<T, Output=T> + ops::Add<T, Output=T>
{
    
    pub fn get_bounds(&self) -> (T, T) {
        let (mut a, mut b, mut c, mut d) = (self.markers[0], self.markers[1], self.markers[2], self.markers[3]);
        
        
        
        if a > c {
            mem::swap(&mut a, &mut c);
        }
        if b > d {
            mem::swap(&mut b, &mut d);
        }
        if a > b {
            mem::swap(&mut a, &mut b);
        }
        if c > d {
            mem::swap(&mut c, &mut d);
        }
        if b > c {
            mem::swap(&mut b, &mut c);
        }
        debug_assert!(a <= b && b <= c && c <= d);
        (a, d)
    }
    
    pub fn intersect(&self, other: &Self) -> bool {
        
        let span = self.get_bounds();
        let other_span = other.get_bounds();
        
        let left = if span.0 < other_span.0 { span.0 } else { other_span.0 };
        let right = if span.1 > other_span.1 { span.1 } else { other_span.1 };
        
        right - left < span.1 - span.0 + other_span.1 - other_span.0
    }
}
pub enum Intersection<T> {
    
    Coplanar,
    
    Outside,
    
    Inside(T),
}
impl<T> Intersection<T> {
    
    pub fn is_outside(&self) -> bool {
        match *self {
            Intersection::Outside => true,
            _ => false,
        }
    }
    
    pub fn is_inside(&self) -> bool {
        match *self {
            Intersection::Inside(_) => true,
            _ => false,
        }
    }
}
#[derive(Debug, PartialEq)]
pub struct Polygon<T, U> {
    
    pub points: [Point3D<T, U>; 4],
    
    pub plane: Plane<T, U>,
    
    
    pub anchor: usize,
}
impl<T: Clone, U> Clone for Polygon<T, U> {
    fn clone(&self) -> Self {
        Polygon {
            points: [
                self.points[0].clone(),
                 self.points[1].clone(),
                 self.points[2].clone(),
                 self.points[3].clone(),
            ],
            plane: self.plane.clone(),
            anchor: self.anchor,
        }
    }
}
impl<T, U> Polygon<T, U> where
    T: Copy + fmt::Debug + ApproxEq<T> +
        ops::Sub<T, Output=T> + ops::Add<T, Output=T> +
        ops::Mul<T, Output=T> + ops::Div<T, Output=T> +
        Zero + One + Float,
    U: fmt::Debug,
{
    
    
    pub fn from_points(
        points: [Point3D<T, U>; 4],
        anchor: usize,
    ) -> Option<Self> {
        let edge1 = points[1] - points[0];
        let edge2 = points[2] - points[0];
        let edge3 = points[3] - points[0];
        let edge4 = points[3] - points[1];
        if edge2.square_length() < T::epsilon() || edge4.square_length() < T::epsilon() {
            return None
        }
        
        
        
        let normal_rough1 = edge1.cross(edge2);
        let normal_rough2 = edge2.cross(edge3);
        let square_length1 = normal_rough1.square_length();
        let square_length2 = normal_rough2.square_length();
        let normal = if square_length1 > square_length2 {
            normal_rough1 / square_length1.sqrt()
        } else {
            normal_rough2 / square_length2.sqrt()
        };
        let offset = -points[0].to_vector()
            .dot(normal);
        Some(Polygon {
            points,
            plane: Plane {
                normal,
                offset,
            },
            anchor,
        })
    }
    
    pub fn from_rect(rect: Rect<T, U>, anchor: usize) -> Self {
        let min = rect.min();
        let max = rect.max();
        let _0 = T::zero();
        Polygon {
            points: [
                min.to_3d(),
                Point3D::new(max.x, min.y, _0),
                max.to_3d(),
                Point3D::new(min.x, max.y, _0),
            ],
            plane: Plane {
                normal: Vector3D::new(T::zero(), T::zero(), T::one()),
                offset: T::zero(),
            },
            anchor,
        }
    }
    
    pub fn from_transformed_rect<V>(
        rect: Rect<T, V>,
        transform: Transform3D<T, V, U>,
        anchor: usize,
    ) -> Option<Self>
    where
        T: Trig + ops::Neg<Output=T>,
    {
        let min = rect.min();
        let max = rect.max();
        let _0 = T::zero();
        let points = [
            transform.transform_point3d(min.to_3d())?,
            transform.transform_point3d(Point3D::new(max.x, min.y, _0))?,
            transform.transform_point3d(max.to_3d())?,
            transform.transform_point3d(Point3D::new(min.x, max.y, _0))?,
        ];
        Self::from_points(points, anchor)
    }
    
    pub fn from_transformed_rect_with_inverse<V>(
        rect: Rect<T, V>,
        transform: &Transform3D<T, V, U>,
        inv_transform: &Transform3D<T, U, V>,
        anchor: usize,
    ) -> Option<Self>
    where
        T: Trig + ops::Neg<Output=T>,
    {
        let min = rect.min();
        let max = rect.max();
        let _0 = T::zero();
        let points = [
            transform.transform_point3d(min.to_3d())?,
            transform.transform_point3d(Point3D::new(max.x, min.y, _0))?,
            transform.transform_point3d(max.to_3d())?,
            transform.transform_point3d(Point3D::new(min.x, max.y, _0))?,
        ];
        
        
        let normal_raw = Vector3D::new(inv_transform.m13, inv_transform.m23, inv_transform.m33);
        let normal_sql = normal_raw.square_length();
        if normal_sql.approx_eq(&T::zero()) || transform.m44.approx_eq(&T::zero()) {
            None
        } else {
            let normal = normal_raw / normal_sql.sqrt();
            let offset = -Vector3D::new(transform.m41, transform.m42, transform.m43)
                .dot(normal) / transform.m44;
            Some(Polygon {
                points,
                plane: Plane {
                    normal,
                    offset,
                },
                anchor,
            })
        }
    }
    
    
    pub fn untransform_point(&self, point: Point3D<T, U>) -> Point2D<T> {
        
        
        let a = self.points[1] - self.points[0];
        let b = self.points[3] - self.points[0];
        let c = point - self.points[0];
        
        let a2 = a.dot(a);
        let ab = a.dot(b);
        let b2 = b.dot(b);
        let ca = c.dot(a);
        let cb = c.dot(b);
        
        let denom = ab * ab - a2 * b2;
        let x = ab * cb - b2 * ca;
        let y = ab * ca - a2 * cb;
        Point2D::new(x, y) / denom
    }
    
    pub fn transform<V>(
        &self, transform: &Transform3D<T, U, V>
    ) -> Option<Polygon<T, V>>
    where
        T: Trig,
        V: fmt::Debug,
    {
        let mut points = [Point3D::origin(); 4];
        for (out, point) in points.iter_mut().zip(self.points.iter()) {
            let mut homo = transform.transform_point3d_homogeneous(*point);
            homo.w = homo.w.max(T::approx_epsilon());
            *out = homo.to_point3d()?;
        }
        
        
        
        Polygon::from_points(points, self.anchor)
    }
    
    
    pub fn is_valid(&self) -> bool {
        let is_planar = self.points
            .iter()
            .all(|p| is_zero(self.plane.signed_distance_to(p)));
        let edges = [
            self.points[1] - self.points[0],
            self.points[2] - self.points[1],
            self.points[3] - self.points[2],
            self.points[0] - self.points[3],
        ];
        let anchor = edges[3].cross(edges[0]);
        let is_winding = edges
            .iter()
            .zip(edges[1..].iter())
            .all(|(a, &b)| a.cross(b).dot(anchor) >= T::zero());
        is_planar && is_winding
    }
    
    
    pub fn is_empty(&self) -> bool {
        (self.points[0] - self.points[2]).square_length() < T::epsilon() ||
        (self.points[1] - self.points[3]).square_length() < T::epsilon()
    }
    
    pub fn contains(&self, other: &Self) -> bool {
        
        self.plane.contains(&other.plane)
    }
    
    
    pub fn project_on(&self, vector: &Vector3D<T, U>) -> LineProjection<T> {
        LineProjection {
            markers: [
                vector.dot(self.points[0].to_vector()),
                vector.dot(self.points[1].to_vector()),
                vector.dot(self.points[2].to_vector()),
                vector.dot(self.points[3].to_vector()),
            ],
        }
    }
    
    pub fn intersect_plane(&self, other: &Plane<T, U>) -> Intersection<Line<T, U>> {
        if other.are_outside(&self.points) {
            debug!("\t\tOutside of the plane");
            return Intersection::Outside
        }
        match self.plane.intersect(&other) {
            Some(line) => Intersection::Inside(line),
            None => {
                debug!("\t\tCoplanar");
                Intersection::Coplanar
            }
        }
    }
    
    pub fn intersect(&self, other: &Self) -> Intersection<Line<T, U>> {
        if self.plane.are_outside(&other.points) || other.plane.are_outside(&self.points) {
            debug!("\t\tOne is completely outside of the other");
            return Intersection::Outside
        }
        match self.plane.intersect(&other.plane) {
            Some(line) => {
                let self_proj = self.project_on(&line.dir);
                let other_proj = other.project_on(&line.dir);
                if self_proj.intersect(&other_proj) {
                    Intersection::Inside(line)
                } else {
                    
                    debug!("\t\tProjection is outside");
                    Intersection::Outside
                }
            }
            None => {
                debug!("\t\tCoplanar");
                Intersection::Coplanar
            }
        }
    }
    fn split_impl(
        &mut self,
        first: (usize, Point3D<T, U>),
        second: (usize, Point3D<T, U>),
    ) -> (Option<Self>, Option<Self>) {
        
        
        debug!("\t\tReached complex case [{}, {}]", first.0, second.0);
        let base = first.0;
        assert!(base < self.points.len());
        match second.0 - first.0 {
            1 => {
                
                let other1 = Polygon {
                    points: [
                        first.1,
                        second.1,
                        self.points[(base + 2) & 3],
                        self.points[base],
                    ],
                    .. self.clone()
                };
                
                let other2 = Polygon {
                    points: [
                        self.points[(base + 2) & 3],
                        self.points[(base + 3) & 3],
                        self.points[base],
                        self.points[base],
                    ],
                    .. self.clone()
                };
                
                self.points = [
                    first.1,
                    self.points[(base + 1) & 3],
                    second.1,
                    second.1,
                ];
                (Some(other1), Some(other2))
            }
            2 => {
                
                let other = Polygon {
                    points: [
                        first.1,
                        self.points[(base + 1) & 3],
                        self.points[(base + 2) & 3],
                        second.1,
                    ],
                    .. self.clone()
                };
                
                self.points = [
                    first.1,
                    second.1,
                    self.points[(base + 3) & 3],
                    self.points[base],
                ];
                (Some(other), None)
            }
            3 => {
                
                let other1 = Polygon {
                    points: [
                        first.1,
                        self.points[(base + 1) & 3],
                        self.points[(base + 3) & 3],
                        second.1,
                    ],
                    .. self.clone()
                };
                
                let other2 = Polygon {
                    points: [
                        self.points[(base + 1) & 3],
                        self.points[(base + 2) & 3],
                        self.points[(base + 3) & 3],
                        self.points[(base + 3) & 3],
                    ],
                    .. self.clone()
                };
                
                self.points = [
                    first.1,
                    second.1,
                    self.points[base],
                    self.points[base],
                ];
                (Some(other1), Some(other2))
            }
            _ => panic!("Unexpected indices {} {}", first.0, second.0),
        }
    }
    
    
    #[deprecated(note = "Use split_with_normal instead")]
    pub fn split(&mut self, line: &Line<T, U>) -> (Option<Self>, Option<Self>) {
        debug!("\tSplitting");
        
        if !is_zero(self.plane.normal.dot(line.dir)) ||
           !is_zero(self.plane.signed_distance_to(&line.origin)) {
            debug!("\t\tDoes not belong to the plane, normal dot={:?}, origin distance={:?}",
                self.plane.normal.dot(line.dir), self.plane.signed_distance_to(&line.origin));
            return (None, None)
        }
        
        let mut cuts = [None; 4];
        for ((&b, &a), cut) in self.points
            .iter()
            .cycle()
            .skip(1)
            .zip(self.points.iter())
            .zip(cuts.iter_mut())
        {
            if let Some(t) = line.intersect_edge(a .. b) {
                if t >= T::zero() && t < T::one() {
                    *cut = Some(a + (b - a) * t);
                }
            }
        }
        let first = match cuts.iter().position(|c| c.is_some()) {
            Some(pos) => pos,
            None => return (None, None),
        };
        let second = match cuts[first+1 ..].iter().position(|c| c.is_some()) {
            Some(pos) => first + 1 + pos,
            None => return (None, None),
        };
        self.split_impl(
            (first, cuts[first].unwrap()),
            (second, cuts[second].unwrap()),
        )
    }
    
    
    
    
    pub fn split_with_normal(
        &mut self, line: &Line<T, U>, normal: &Vector3D<T, U>,
    ) -> (Option<Self>, Option<Self>) {
        debug!("\tSplitting with normal");
        
        let mut sides = [T::zero(); 4];
        let (mut cut_positive, mut cut_negative) = (None, None);
        for (side, point) in sides.iter_mut().zip(&self.points) {
            *side = normal.dot(*point - line.origin);
        }
        
        for (i, ((&side1, point1), (&side0, point0))) in sides[1..]
            .iter()
            .chain(iter::once(&sides[0]))
            .zip(self.points[1..].iter().chain(iter::once(&self.points[0])))
            .zip(sides.iter().zip(&self.points))
            .enumerate()
        {
            
            let cut = if side0 < T::zero() && side1 >= T::zero() {
                &mut cut_positive
            } else if side0 > T::zero() && side1 <= T::zero() {
                &mut cut_negative
            } else {
                continue;
            };
            
            
            
            
            
            
            
            
            
            let point = (*point0 * side1.abs() + point1.to_vector() * side0.abs()) / (side0 - side1).abs();
            debug_assert_eq!(*cut, None);
            *cut = Some((i, point));
        }
        
        if let (Some(first), Some(mut second)) = (cut_positive, cut_negative) {
            if second.0 < first.0 {
                second.0 += 4;
            }
            self.split_impl(first, second)
        } else {
            (None, None)
        }
    }
}