using System;
using System.Windows.Forms;
using System.Threading;
using System.Drawing;
using Microsoft.DirectX;

namespace Bil_LD
{
    public class ViewControl : UserControl
    {
        private ViewTypes _ViewType;
        private GameEngine _GameEngine;
        public bool _Running;
        public Thread _ThreadRender;
        public FormLD _ParentForm;

        public ViewTypes ViewType
        {
            get { return _ViewType; }
            set { _ViewType = value; }
        }

        public enum ViewTypes
        {
            Top,
            Left,
            Right,
            Render
        }        

        public ViewControl(GameEngine gameengine, FormLD parent)
        {
            AllowDrop = true;

            _GameEngine = gameengine;

            _ParentForm = parent;

            SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.Opaque, true);

            _ThreadRender = new Thread(new ThreadStart(Render));
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            if (!_ThreadRender.IsAlive)
                _ThreadRender.Start();            
        }

        private void Render()
        {
            _Running = true;

            while (_Running)
            {
                try
                {
                    if (_ViewType == ViewTypes.Top)
                    {
                        //_GameEngine.Setup();
                        _GameEngine.Render(_ViewType);
                    }

                    Thread.Sleep(1);
                }
                catch (Exception)
                {
                    Console.WriteLine("Render Fail");
                }                
            }
        }

        protected override void Dispose(bool disposing)
        {
            _Running = false;
            base.Dispose(disposing);
        }

        protected override void OnDragEnter(DragEventArgs drgevent)
        {
            if (drgevent.Data.GetDataPresent(typeof(string)))
            {
                drgevent.Effect = DragDropEffects.Copy;
            }
        }

        protected override void OnDragDrop(DragEventArgs drgevent)
        {
            string file = (string)drgevent.Data.GetData(typeof(string));

            GameObject obj = new GameObject(_GameEngine.gameDevice, file,
                new Vector3(_GameEngine.Camera_Position.X, 0, _GameEngine.Camera_Position.Z));

            if (!obj.CreateMesh(_GameEngine.gameDevice))
                return;


            _GameEngine._RenderableItems.Add(obj);

            _ParentForm.RefreshCurrentGameObjects();

            _GameEngine.CurrentObject = null;
        }

    }
}
