﻿using UnityEngine;
using UnityEngine.Tilemaps;
using AC;

namespace AC.JRPG
{

	public class GridMovement : MonoBehaviour
	{

		public Tilemap tilemap;
		private Grid grid;
		private Char acCharacter;


		private void Start ()
		{
			acCharacter = GetComponent <Char> ();
			grid = tilemap.transform.parent.GetComponentInParent<Grid> ();
		}

		void Update()
		{
			if (!KickStarter.stateHandler.IsInGameplay () 
				|| (!acCharacter.IsPlayer || KickStarter.settingsManager.movementMethod == MovementMethod.PointAndClick)
				|| acCharacter.IsMovingAlongPath ())
			{
				return;
			}
			
			Vector2 moveInput = new Vector2 (KickStarter.playerInput.InputGetAxis ("Horizontal"), KickStarter.playerInput.InputGetAxis ("Vertical"));
			if (moveInput.sqrMagnitude < 0.01f) return;

			float cellWidth = grid.cellSize.x;
			float cellHeight = grid.cellSize.y;

			float moveX = moveInput.x == 0 ? 0f : moveInput.x > 0f ? 1f : -1f;
			float moveY = moveInput.y == 0 ? 0f : moveInput.y > 0f ? 1f : -1f;
			Vector3 newRelativePosition = new Vector3 (moveX * cellWidth, moveY * cellHeight, 0f);

			Vector3 targetWorld = acCharacter.transform.position + newRelativePosition;
			Vector3Int cellPosition = tilemap.WorldToCell (targetWorld);
				
			bool hasTile = tilemap.GetTile (cellPosition);
			if (!hasTile) return;

			Vector3 cellWorld = tilemap.CellToWorld (cellPosition);
			cellWorld += new Vector3 (cellWidth * 0.5f, cellHeight * 0.5f);

			acCharacter.MoveToPoint (cellWorld);
		}

	}

}