using System;

namespace HPJ.Simulation.Map
{
    public class AgentMap
    {
        /// <summary>
        /// Base map related to this map
        /// </summary>
        public Map Base { get; protected set; }
        /// <summary>
        /// Tile that descripe the agent ownership
        /// </summary>
        public ushort[,] Tiles { get; protected set; }

        /// <summary>
        /// Initializes the agent map based on the base map
        /// </summary>
        /// <param name="baseMap"></param>
        public AgentMap(Map baseMap)
        {
            Base = baseMap;

            Tiles = new ushort[baseMap.Settings.MapWidth, baseMap.Settings.MapHeight];
        }

        /// <summary>
        /// Disowns this tile so other agents can claim it or to know its availible
        /// </summary>
        /// <param name="ownedTile"></param>
        public void DisownTile(IntVector2 ownedTile, ushort ID)
        {
            if (ownedTile.x < 0 || ownedTile.y < 0 || ownedTile.x >= Base.Settings.MapWidth || ownedTile.y >= Base.Settings.MapHeight)
            {
                return;
            }

            if (Tiles[ownedTile.x, ownedTile.y] == ID)
            {
                Tiles[ownedTile.x, ownedTile.y] = 0;
            }
        }

        /// <summary>
        /// Attempts to claim a tile for a specified ID
        /// </summary>
        /// <param name="newTilePosition"></param>
        /// <param name="ID"></param>
        /// <returns></returns>
        public bool ClaimTile(IntVector2 newTilePosition, ushort ID)
        {
            if (newTilePosition.x < 0 || newTilePosition.y < 0 || newTilePosition.x >= Base.Settings.MapWidth || newTilePosition.y >= Base.Settings.MapHeight)
            {
                return false;
            }

            if (Tiles[newTilePosition.x, newTilePosition.y] == 0)
            {
                Tiles[newTilePosition.x, newTilePosition.y] = ID;
                return true;
            }

            return false;
        }

        internal bool IsBlocked(int x, int y, ushort CompareID)
        {
            return Tiles[x, y] != 0 && Tiles[x, y] != CompareID;
        }

        public bool ValidTileForAgent(ushort simNavigationAgentID, int x, int y)
        {
            if (Tiles[x, y] == 0 || Tiles[x, y] == simNavigationAgentID)
            {
                return true;
            }

            return false;
        }
    }
}