using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using EVE.EVEThreading;
using System.Threading;
using System.Diagnostics;
using System.Collections.ObjectModel;

namespace EVE.EVELogic
{
    public class EVEUpdateManager
    {
        public Dictionary<int,EVEUnit> gameLogicObjects { get; set; }
        private EVEDoubleBuffer doubleBuffer;
        private GameTime gameTime;


        protected EVEMessageBuffer messageBuffer;
        protected EVEGame game;

        public Thread RunningThread { get; set; }
        volatile public Stopwatch FrameWatch;

        public EVEUpdateManager(EVEDoubleBuffer doubleBuffer, EVEGame game)
        {
            this.doubleBuffer = doubleBuffer;
            this.game = game;
            this.gameLogicObjects = new Dictionary<int,EVEUnit>();
            FrameWatch = new Stopwatch();
            FrameWatch.Reset();
        }

        private void run()
        {
            #if XBOX
                Thread.CurrentThread.SetProcessorAffinity(4);
            #endif

            while (true)
            {
                DoFrame();
            }
        }

        public virtual void addUnit(int uID,EVEUnit unit)
        {
            gameLogicObjects.Add(uID,unit);
        }

        public virtual void addUnit(EVEUnit unit)
        {
            gameLogicObjects.Add(unit.uID, unit);
        }

        public void StartOnNewThread()
        {
            ThreadStart ts = new ThreadStart(run);
            RunningThread = new Thread(ts);
            RunningThread.Start();
        }

        public void DoFrame()
        {
            doubleBuffer.StartUpdateProcessing(out messageBuffer, out gameTime);
            FrameWatch.Reset();
            FrameWatch.Start();
            this.Update(gameTime);
            FrameWatch.Stop();
            doubleBuffer.SubmitUpdate();
        }

        public virtual void Update(GameTime gameTime)
        {
        }
    }
}
