using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using Interop;
using OpenTK;

namespace Fuseren
{
    public class AIEngine
    {
        readonly InteropService _interop;
        readonly GameInfo _gameInfo;
        readonly MapInfo _mapInfo;
        readonly Navigation _navigation;
	    readonly ItemUsability _itemUsability;
        DateTime _lastTime = DateTime.Now;
        int _lastTarget = 0;

        public Bitmap CurrentBitmap { get { return _navigation.CurrentBitmap; } }
        public PlayerState OldState { get { return _navigation.OldState; } }

        public AIEngine(InteropService interop)
        {
            _interop = interop;
            _gameInfo = _interop.QueryForState<GameInfo>().Result;
            _mapInfo = _gameInfo.MapInfo;
	        _itemUsability = new ItemUsability(_mapInfo);
            var heatmapGenerator = HeatmapGenerator.StartAsync(_mapInfo, Enumerable.Empty<BoxData>(), (_mapInfo.TileWidth + _mapInfo.TileHeight) * 0.2);
            heatmapGenerator.ContinueWith(
                t =>
                {
                    var heatmap = t.Result;
                    var bitmap = heatmap.ToBitmap();
                    bitmap.Save("test.png", ImageFormat.Png);
                });

            _navigation = new Navigation(heatmapGenerator, _gameInfo);
            _interop.Send(0);
        }

        public void Run()
        {
            var gameStateTask = _interop.QueryForState<GameState>().Result;
            
            var curTime = DateTime.Now;
            var dt = new TimeSpan((curTime - _lastTime).Ticks).TotalSeconds;
            _lastTime = curTime;

            var steerKeys = _navigation.Steer(dt, gameStateTask);
			_interop.Send((byte)((byte)steerKeys | (byte)_itemUsability.CreateCommands(_gameInfo.PlayerId, _navigation.CurrentPath, gameStateTask)));
        }
    }
}