use crate::{
    intersections::{Intersection, Intersections},
    materials::Material,
    matrices::Matrix4x4,
    rays::Ray,
    tuples::{dot, Tuple},
};

#[derive(Debug, PartialEq, Clone)]
/// Sphere represents the unit-sphere (radius of unit 1.) at the origin 0., 0., 0.
pub struct Sphere {
    // TODO(wathiede): cache inverse to speed up intersect.
    transform: Matrix4x4,
    inverse_transform: Matrix4x4,
    pub material: Material,
}

impl Default for Sphere {
    /// # Examples
    /// ```
    /// use rtchallenge::{materials::Material, matrices::Matrix4x4, spheres::Sphere};
    ///
    /// // A sphere's default transform is the identity matrix.
    /// let s = Sphere::default();
    /// assert_eq!(s.transform(), Matrix4x4::identity());
    ///
    /// // It can be changed by directly setting the transform member.
    /// let mut s = Sphere::default();
    /// let t = Matrix4x4::translation(2., 3., 4.);
    /// s.set_transform ( t.clone());
    /// assert_eq!(s.transform(), t);
    ///
    /// // Default Sphere has the default material.
    /// assert_eq!(s.material, Material::default());
    /// // It can be overridden.
    /// let mut s = Sphere::default();
    /// let mut m = Material::default();
    /// m.ambient = 1.;
    /// s.material = m.clone();
    /// assert_eq!(s.material, m);

    /// ```
    fn default() -> Sphere {
        Sphere {
            transform: Matrix4x4::identity(),
            inverse_transform: Matrix4x4::identity(),
            material: Material::default(),
        }
    }
}

impl Sphere {
    /// Find the normal at the point on the sphere.
    ///
    /// # Examples
    /// ```
    /// use rtchallenge::{matrices::Matrix4x4, spheres::Sphere, tuples::Tuple};
    ///
    /// // Normal on X-axis
    /// let s = Sphere::default();
    /// let n = s.normal_at(Tuple::point(1., 0., 0.));
    /// assert_eq!(n, Tuple::vector(1., 0., 0.));
    ///
    /// // Normal on Y-axis
    /// let s = Sphere::default();
    /// let n = s.normal_at(Tuple::point(0., 1., 0.));
    /// assert_eq!(n, Tuple::vector(0., 1., 0.));
    ///
    /// // Normal on Z-axis
    /// let s = Sphere::default();
    /// let n = s.normal_at(Tuple::point(0., 0., 1.));
    /// assert_eq!(n, Tuple::vector(0., 0., 1.));
    ///
    /// // Normal on a sphere at a nonaxial point.
    /// let s = Sphere::default();
    /// let n = s.normal_at(Tuple::point(
    ///     3_f32.sqrt() / 3.,
    ///     3_f32.sqrt() / 3.,
    ///     3_f32.sqrt() / 3.,
    /// ));
    /// assert_eq!(
    ///     n,
    ///     Tuple::vector(3_f32.sqrt() / 3., 3_f32.sqrt() / 3., 3_f32.sqrt() / 3.,)
    /// );
    /// // Normals returned are normalized.
    /// let s = Sphere::default();
    /// let n = s.normal_at(Tuple::point(
    ///     3_f32.sqrt() / 3.,
    ///     3_f32.sqrt() / 3.,
    ///     3_f32.sqrt() / 3.,
    /// ));
    /// assert_eq!(n, n.normalize());
    ///
    /// // Compute the normal on a translated sphere.
    /// let mut s = Sphere::default();
    /// s.set_transform ( Matrix4x4::translation(0., 1., 0.));
    /// let n = s.normal_at(Tuple::point(0., 1.70711, -0.70711));
    /// assert_eq!(n, Tuple::vector(0., 0.70711, -0.70711));

    /// // Compute the normal on a transformed sphere.
    /// use std::f32::consts::PI;
    ///
    /// let mut s = Sphere::default();
    /// s.set_transform ( Matrix4x4::scaling(1.,0.5,1.) * Matrix4x4::rotation_z(PI/5.));
    /// let n = s.normal_at(Tuple::point(0., 2_f32.sqrt()/2., -2_f32.sqrt()/2.));
    /// assert_eq!(n, Tuple::vector(0., 0.97014, -0.24254));
    /// ```
    pub fn normal_at(&self, world_point: Tuple) -> Tuple {
        let object_point = self.inverse_transform * world_point;
        let object_normal = object_point - Tuple::point(0., 0., 0.);
        let mut world_normal = self.inverse_transform.transpose() * object_normal;
        world_normal.w = 0.;
        world_normal.normalize()
    }

    pub fn transform(&self) -> Matrix4x4 {
        self.transform
    }
    pub fn set_transform(&mut self, t: Matrix4x4) {
        self.transform = t;
        self.inverse_transform = t.inverse();
    }
}

/// Intersect a ray with a sphere.
///
/// # Examples
/// ```
/// use rtchallenge::{
///     intersections::{Intersection, Intersections},
///     matrices::Matrix4x4,
///     rays::Ray,
///     spheres::{intersect, Sphere},
///     tuples::Tuple,
/// };
///
/// // A ray intersects a sphere in two points.
/// let r = Ray::new(Tuple::point(0., 0., -5.), Tuple::vector(0., 0., 1.));
/// let s = Sphere::default();
/// let xs = intersect(&s, &r);
/// assert_eq!(
///     xs,
///     Intersections::new(vec![Intersection::new(4., &s), Intersection::new(6., &s)])
/// );
///
/// // A ray intersects a sphere at a tangent.
/// let r = Ray::new(Tuple::point(0., 2., -5.), Tuple::vector(0., 0., 1.));
/// let s = Sphere::default();
/// let xs = intersect(&s, &r);
/// assert_eq!(xs, Intersections::default());
///
/// // A ray originates inside a sphere.
/// let r = Ray::new(Tuple::point(0., 0., 0.), Tuple::vector(0., 0., 1.));
/// let s = Sphere::default();
/// let xs = intersect(&s, &r);
/// assert_eq!(
///     xs,
///     Intersections::new(vec![Intersection::new(-1., &s), Intersection::new(1., &s)])
/// );
///
/// // A sphere is behind a ray.
/// let r = Ray::new(Tuple::point(0., 0., 5.), Tuple::vector(0., 0., 1.));
/// let s = Sphere::default();
/// let xs = intersect(&s, &r);
/// assert_eq!(
///     xs,
///     Intersections::new(vec![Intersection::new(-6., &s), Intersection::new(-4., &s)])
/// );
///
/// // Intersect a scaled sphere with a ray.
/// let r = Ray::new(Tuple::point(0., 0., -5.), Tuple::vector(0., 0., 1.));
/// let mut s = Sphere::default();
/// s.set_transform(Matrix4x4::scaling(2., 2., 2.));
/// let xs = intersect(&s, &r);
/// assert_eq!(xs.len(), 2, "xs {:?}", xs);
/// assert_eq!(xs[0].t, 3., "xs {:?}", xs);
/// assert_eq!(xs[1].t, 7., "xs {:?}", xs);
///
/// // Intersect a translated sphere with a ray.
/// let r = Ray::new(Tuple::point(0., 0., -5.), Tuple::vector(0., 0., 1.));
/// let mut s = Sphere::default();
/// s.set_transform(Matrix4x4::translation(5., 0., 0.));
/// let xs = intersect(&s, &r);
/// assert_eq!(xs.len(), 0);
/// ```
pub fn intersect<'s>(sphere: &'s Sphere, ray: &Ray) -> Intersections<'s> {
    let ray = ray.transform(sphere.inverse_transform);
    let sphere_to_ray = ray.origin - Tuple::point(0., 0., 0.);
    let a = dot(ray.direction, ray.direction);
    let b = 2. * dot(ray.direction, sphere_to_ray);
    let c = dot(sphere_to_ray, sphere_to_ray) - 1.;
    let discriminant = b * b - 4. * a * c;
    if discriminant < 0. {
        Intersections::default()
    } else {
        Intersections::new(vec![
            Intersection::new((-b - discriminant.sqrt()) / (2. * a), &sphere),
            Intersection::new((-b + discriminant.sqrt()) / (2. * a), &sphere),
        ])
    }
}
