﻿using BringMeHome.Gameplay.Actors;
using BringMeHome.Gameplay.Behaviours;
using BringMeHome.Misc;
using Duality;
using Duality.Components;
using Duality.Drawing;
using Duality.Input;
using Duality.Resources;

namespace BringMeHome.Gameplay
{
	[RequiredComponent(typeof(GameManager))]
	public class InputManager : Singleton<InputManager>, ICmpInitializable, ICmpUpdatable
	{
		public KeyConfiguration KeyConfiguration
		{
			get { return keyConfiguration; }
			set { keyConfiguration = value; }
		}

		private KeyConfiguration keyConfiguration = new KeyConfiguration();

		[DontSerialize]
		private GameManager gameManager = null;

		[DontSerialize]
		private Player player = null;

		public void OnInit(InitContext context)
		{
			if (context == InitContext.Activate)
			{
				gameManager = GameObj.GetComponent<GameManager>();
				player = gameManager.Player;
			}
		}

		public void OnShutdown(ShutdownContext context)
		{
		}

		public void OnUpdate()
		{
			if (player == null) return;

			// mouse stuff
			var mouse = DualityApp.Mouse;
			var attack1 = mouse.ButtonHit(keyConfiguration.Attack);

			// keyboard stuff
			var keyboard = DualityApp.Keyboard;
			var keyLeft = keyboard.KeyPressed(keyConfiguration.MoveLeft);
			var keyRight = keyboard.KeyPressed(keyConfiguration.MoveRight);
			var keyUp = keyboard.KeyPressed(keyConfiguration.MoveUp);
			var keyDown = keyboard.KeyPressed(keyConfiguration.MoveDown);
			var keySprint = keyboard.KeyPressed(keyConfiguration.Sprint);
			var keyAbort = keyboard.KeyHit(Key.Escape);
			var keyInventory = keyboard.KeyHit(Key.I);

			if (attack1)
			{
				var mousePos = Scene.Current.FindComponent<Camera>().GetSpaceCoord(mouse.Pos);
				var attackBehaviour = player?.GameObj.GetComponent<AttackBehaviour>();
				attackBehaviour?.Attack(mousePos.Xy);
			}

			// move left
			if (keyLeft)
			{
				player?.Move(-Vector2.UnitX);
			}

			// move right
			if (keyRight)
			{
				player?.Move(Vector2.UnitX);
			}

			// move up
			if (keyUp)
			{
				player?.Move(-Vector2.UnitY);
			}

			// move down
			if (keyDown)
			{
				player?.Move(Vector2.UnitY);
			}

			player?.Sprint(keySprint);

			if (!keyUp && !keyDown && !keyLeft && !keyRight)
				player.Stop();
		}
	}
}