using UnityEngine;

public class ObjectPlaceholder : UnitPlaceholder
{
    public GameObject Prefab { get; set; }

    public override void Place()
    {
        base.Place();
        Prefab.Create(transform.position, parent : LevelManager.Instance.LevelTransform);
    }

    public override bool CanBePlacedHere()
    {
        var objsOnPosition = LevelManager.Instance.GetAll<ILevelObject>(obj => obj.Position.IsContainedIn(transform.position));
        var positionIsCollidable = objsOnPosition.Exists(obj => obj.IsCollidable);

        // If an ally is on the tile, we can't place anything here
        foreach (var item in objsOnPosition)
        {
            if (item is Ally) 
            {
                return false;
            }
        }

        var defaultUnitCost = GlobalConfig.Instance.Current.populationCostPerUnit;
        return !positionIsCollidable 
            && LevelBoundCache.Contains(transform.position)
            && ResourceManager.Instance.EnoughFor(Rock, Wood, Food)
            && (Prefab.GetComponent<Building>()
            || ResourceManager.Instance.EnoughPopulationFor(defaultUnitCost)) 
            && IsHarvesterAndAllowed();
    }

    private bool IsHarvesterAndAllowed()
    {
        Ally unit = Prefab.GetComponent<Ally>();
        
        // Get info
        LevelTile pointedTile = LevelManager.Instance.Get<LevelTile>(obj => obj.Position.IsContainedIn(transform.position));

        return unit is not Harvester || (unit is Harvester && IsAllowedTile(pointedTile));
    }

    private bool IsAllowedTile(LevelTile pointedTile)
    {
        return pointedTile is ResourceTile;
    }
}