using System;

namespace Tutor_RT
{
    public class Sphere : AObject
    {
        public V3 center;
        public double radius;
        public Color_0_to_1 color;

        #region Constructors

        public Sphere()
        {
            center = new V3();
            radius = 1;
            color = new Color_0_to_1(0, 0.5, 0.5, 0.5);
        }

        public Sphere(V3 m, double r, Color_0_to_1 col)
        {
            center = m;
            radius = r;
            color = col;
        }

        public V3 get_m    
        {
            get { return center; }
        }

        public double get_r    
        {
            get { return radius; }
        }

        public override Color_0_to_1 getColor    
        {
            get { return color; }
        }

        #endregion

        public override V3 get_n(V3 point)
        {
            V3 n0 = (point - center).normalize;
            return n0;
        }

        public override double Lambda_min(Ray ray)
        {
            //double a = 1; because a=u*u; ray g:x=a+r*u; u is normalized
            double b = 2 * (ray.get_a - get_m) * ray.get_u;
            double c = (ray.get_a - get_m) * (ray.get_a - get_m) - radius*radius;
            //double discriminant = b * b - 4 * a * c;
            double discriminant = b * b - 4 * c;

            if (discriminant > 0)//ray intersects sphere
            {
                //(-b +- sqrt(b^2-4ac))/(2a)
                double r1 = (-b - Math.Sqrt(discriminant)) / 2.0 - 0.0001;//a=1
                if (r1 > 0) return r1;//closest point of intersection
                else
                {//Camera is inside the sphere
                    double r2 = (-b + Math.Sqrt(discriminant)) / 2.0 - 0.0001;
                    return r2;
                }
            } else return -1;//no intersection of ray and sphere
        }
    }
}
