using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using OpenGLSupport;

namespace PG_Sim
{
    public partial class Operator : Form
    {
        // time of start application
        public DateTime startTime = DateTime.Now;

        // Threads
        Thread communication;
        Thread physics;

        // init flag
        bool initialize=false;
        
        public Operator()
        {
            InitializeComponent();

            // switch on OpenGL window
            OpenGL_Window.SwitchOn(OpenGL_Window.Handle);

            // rendering method
            OpenGL_Window.OnRender += new OpenGLSupport.OpenGLCanvas.OpenGLCanvasOnRender(RenderControl);

            // Rendering, physics initialization
            Physics.Init();
            Renderer.Init();

            // controll driver init 
            Controll.Init(this);
            communication = new Thread(Controll.SaveValues);
            communication.Name = "Communication";
            communication.IsBackground = true;
            communication.Start();

            // solver thread init
            Physics.run_solver = true;
            physics = new Thread(Physics.Solver);
            physics.Name = "Physics";
            physics.IsBackground = true;
            physics.Start();
        }

        public void RenderControl()
        {
            OpenGL_Window.BeginRender(100000);
            
            Renderer.Scene(); 

            // finish render and invalidate (for refresh)
            OpenGL_Window.EndRender();
            OpenGL_Window.Invalidate();
        }

        private void MainWindow_Closed(object sender, FormClosedEventArgs e)
        {
            // renderer release texture and display lists
            Renderer.Destroy();

            // turn off physics solver
            Physics.run_solver = false;

            // switch off OpenGL
            OpenGL_Window.SwitchOff();

            // HID destroy
            Controll.Destroy();
        }
        
        // Pushed button to exit application
        private void EndApp(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void keyInput(object sender, KeyEventArgs e)
        {
            // send event to right class
            Controll.keyboardInput(e, physics);
        }
    }
}
