using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;

using Spark3D.Algebra3D;
using Spark3D.LightSources;
using Spark3D.Objects3D;
using Spark3D.Projector3D;
using Spark3D.View2D.Widgets;
using Spark3D.View2D.Widgets.Text;

namespace Spark3D
{
    /// <summary>
    /// Control to view 3D renderings
    /// </summary>
    public class ViewPort : Control
    {
        #region declarations
        /// <summary>
        /// The main graphics object for drawing in the paint event
        /// </summary>
        private Graphics g;
        /// <summary>
        /// Bitmap for double buffering
        /// </summary>
        private Bitmap _backBuffer;
        /// <summary>
        /// Timer for creating animations
        /// </summary>
        private Timer timer;
        /// <summary>
        /// Timer for counting Frames Per Second
        /// </summary>
        private Timer fps;
        /// <summary>
        /// The number of paints each second, incremented each repaint.
        /// </summary>
        int paints = 0;
        /// <summary>
        /// The number of paints in string format, that is drawn to the screen.
        /// </summary>
        String numPaints;
        /// <summary>
        /// All widgets
        /// </summary>
        List<Widget> Widgets;
        /// <summary>
        /// Info widget
        /// </summary>
        WLabel InfoText;
        /// <summary>
        /// Objects that move around in the viewport.
        /// </summary>
        IList<IObject3D> Contained3DObjects;
        /// <summary>
        /// The lightsource for the viewport
        /// </summary>
        IList<ILightSource> ContainedLights;
        /// <summary>
        /// Used to project from 3D to 2D with perspective.
        /// </summary>
        private IProjector3D m_oProjector;
        /// <summary>
        /// Location of veiwers eyeball!
        /// </summary>
        private double m_vViewDistance; // r
        private Vector3D m_vViewAngles; //(Theta-X,Theta-Y,Theta-Z)
        private Vector3D m_vViewAngleDeltas;
        private bool m_bAnimate = false;

        #endregion declarations

        /// <summary>
        /// Constructor
        /// </summary>
        public ViewPort()
        {
            Widgets = new List<Widget>();
            Contained3DObjects = new List<IObject3D>();
            ContainedLights = new List<ILightSource>();

            m_vViewDistance = 0;
            m_vViewAngles = new Vector3D(0, 0, 0);
            m_vViewAngleDeltas = new Vector3D(0, 0, 0);

            // Set up Control.
            InitializeComponent();

            timer.Start();
            fps.Start();
        }
        /// <summary>
        /// Set up any controls that will be drawn
        /// </summary>
        private void InitializeComponent()
        {
            this.SuspendLayout();
            this.BackColor = Color.LightGray;
            this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.DoubleBuffer, true);
            this.Anchor = (AnchorStyles.Bottom | AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right);
            // Set up the info widget
            Widget InfoBox = new Widget(100, 55, 10, 10);
            InfoBox.Text = "Info";
            Widgets.Add(InfoBox);
            InfoText = new WLabel();
            InfoBox.AddWidget(InfoText);
            //Set the timer to tick every 100ms
            this.timer = new Timer();
            timer.Tick += new EventHandler(timer_Tick);
            timer.Interval = 1;
            //Set up FPS timer to tick every 1000ms
            this.fps = new Timer();
            fps.Tick += new EventHandler(fps_tick);
            fps.Interval = 1000;
            this.ResumeLayout(false);
        }
        /// <summary>
        /// Fired when the timer is ticked
        /// </summary>
        private void timer_Tick(object sender, EventArgs e)
        {
            if (m_bAnimate) 
                MoveMe();
            this.Refresh();
        }
        /// <summary>
        /// Fired when the FPS timer is ticked (Every 1000ms)
        /// </summary>
        private void fps_tick(object sender, EventArgs e)
        {
            Spark3D.Util.ConsoleOut.Debug("FPS: " + numPaints);
            numPaints = paints.ToString();
            paints = 0;
            Refresh();
        }
        /// <summary>
        /// Paint Event - Used to draw the 3D shapes
        /// </summary>
        protected override void OnPaint(PaintEventArgs e)
        {
            paints++;
            if (_backBuffer == null)
            {
                _backBuffer = new Bitmap(this.ClientRectangle.Width, this.ClientRectangle.Height);
            }
            g = Graphics.FromImage(_backBuffer);
            g.FillRectangle(new SolidBrush(this.BackColor), e.ClipRectangle.X, e.ClipRectangle.Y, e.ClipRectangle.Width, e.ClipRectangle.Height);
            g.SmoothingMode = SmoothingMode.HighQuality;

            /* Do painting stuff here */

            //Draw the FPS count
            InfoText.Text = "FPS: " + numPaints;
            // Draw the polygons from the animated objects
            foreach (IObject3D o3 in Contained3DObjects)
            {
                DrawPolygons(g, o3.Polygons(m_oProjector));
            }
            // Draw the widgets
            foreach (Widget bw in Widgets)
            {
                bw.Draw(ref g);
            }
            //Clean up
            g.Dispose();
            //Draw to screen
            e.Graphics.DrawImageUnscaled(_backBuffer, 0, 0);
        }
        /// <summary>
        /// Draws lines to the screen
        /// </summary>
        /// <param name="g">The Graphics object to draw with</param>
        /// <param name="lines">The list of lines to draw</param>
        private void DrawPolygons(Graphics g, IList<Polygon2D> polygons)
        {
            Point shift = new Point(Size.Width / 2, Size.Height / 2);
            foreach (Polygon2D p in polygons)
            {
                Brush b = new SolidBrush(p.itsColour);
                p.Shift(shift);
                // Potential overflow exception, look into better way of drawing?
                g.FillPolygon(b, p.itsVerticies);
            }
        }
        /// <summary>
        /// Moves the viewing position
        /// </summary>
        public void MoveMe()
        {
            m_vViewAngles += m_vViewAngleDeltas;
            m_oProjector.MoveView(m_vViewAngles);
        }
        /// <summary>
        /// Inserts an IProjector3D
        /// </summary>
        /// <param name="projector">The IProjector3D to add</param>
        public void Insert(IProjector3D projector)
        {
            m_oProjector = projector;
            m_oProjector.MoveView(m_vViewDistance);
            m_oProjector.MoveView(m_vViewAngles);
        }
        /// <summary>
        /// Inserts an Object3D into the list of drawn objects.  Add all object before adding any lights.
        /// </summary>
        /// <param name="o3d">The Object3D to add</param>
        public void Insert(IObject3D o3d)
        {
            Contained3DObjects.Add(o3d);
        }
        /// <summary>
        /// Inserts an ILightSource
        /// </summary>
        /// <param name="light">The ILightSource to add</param>
        public void Insert(ILightSource light)
        {
            ContainedLights.Add(light);
            foreach (IObject3D o3d in Contained3DObjects)
            {
                o3d.Illuminate(light); //Double dispatch to get the polygons into the light source.
            }
        }
        /// <summary>
        /// Prevent the background from being painted
        /// </summary>
        protected override void OnPaintBackground(PaintEventArgs e) { }
        /// <summary>
        /// Resize the buffered image to accomodate the new size of the control
        /// </summary>
        protected override void OnSizeChanged(EventArgs e)
        {
            if (_backBuffer != null)
            {
                _backBuffer.Dispose();
                _backBuffer = null;
            }
            base.OnSizeChanged(e);
        }
        /// <summary>
        /// Distance of camera from the origin.
        /// </summary>
        public double CameraDistance
        {
            get { return m_vViewDistance; }
            set
            {
                m_vViewDistance = value;
                if (m_oProjector != null)
                    m_oProjector.MoveView(m_vViewDistance);
                Refresh();
            }
        }
        /// <summary>
        /// Absolute camera angle
        /// </summary>
        public Vector3D CameraAngle
        {
            get { return m_vViewAngles; }
            set
            {
                m_vViewAngles = value;
                if (m_oProjector != null)
                    m_oProjector.MoveView(m_vViewAngles);
                Refresh();
            }
        }
        /// <summary>
        /// How fast does does the camera angle move when animating.
        /// </summary>
        public Vector3D CameraAngleDeltas
        {
            get { return m_vViewAngleDeltas; }
            set
            {
                m_vViewAngleDeltas = value;
            }
        }

        /// <summary>
        /// How big is the camera lens
        /// </summary>
        public double FieldOfView
        {
            set
            {
                m_oProjector.FieldOfView = value;
                Refresh();
            }
        }
        /// <summary>
        /// Start the animation
        /// </summary>
        public void Animate()
        {
            m_bAnimate = true;
        }
        /// <summary>
        /// Stop the animation
        /// </summary>
        public void Freeze()
        {
            m_bAnimate = false;
        }
    }
}
