using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class LDCollectionTowerComponent : MonoBehaviour
{
    public float TimeBetweenCollectionPulses = 0.1f;
    private float fPulseDelay;
    public TM_SpriteAnimator myAnimComponent;
    public LDGameActor myGameActor;

    public GameObject Prefab_CollectionParticle;

    public AudioClip clip_GetEnergy;
    public AudioClip clip_NewWorker;
    public GameObject Prefab_WorkerToSpawn;
    public GameObject Prefab_ParticleSpawn;

    public int EnergyRequiredToSpawnWorker;
    private int iCurrentEnergy;

    private GameManager theGame;

    public void Start()
    {
        theGame = GameManager.GetGame();
        theGame.theAIManager.RegisterLandmark(myGameActor);
    }

    public void OnTriggerEnter2D(Collider2D hitObject)
    {
        OnHitObject(hitObject.gameObject);
    }

    public void OnTriggerStay2D(Collider2D hitObject)
    {
        OnHitObject(hitObject.gameObject);
    }

    protected bool OnHitObject(GameObject hitObject)
    {
        Debug.Log("Something is in my range! " + hitObject.name);
        LDPlayer player = hitObject.GetComponent<LDPlayer>();
        if (player != null)
        {
            if (fPulseDelay <= 0f && player.iEnergyCollected > 0)
            {
                StartCollectOneEnergy(player);
            }
            else
            {
                fPulseDelay -= Time.deltaTime;
            }
        }
        return true;
    }

    void StartCollectOneEnergy(LDPlayer player)
    {
        player.iEnergyCollected--;

        GameObject go = Instantiate(Prefab_CollectionParticle);
        LDPickupProjectile pp = go.GetComponent<LDPickupProjectile>();
        pp.myGameActor = pp.GetComponent<LDGameActor>();
        pp.myGameActor.vWorldPos = player.GetPickupCollectionPosition();

        pp.ForceBeginCollection(myGameActor, OnEnergyReachesTower);
        fPulseDelay = TimeBetweenCollectionPulses;
    }

    public void OnEnergyReachesTower(LDPickupProjectile proj)
    {
        myAnimComponent.StartIfNotRunning("collect");
        myAnimComponent.behavior = EShepAnimBehavior.play_once_then_idle;

        TM_AudioManager.PlayClip(clip_GetEnergy);

        iCurrentEnergy++;
        if (iCurrentEnergy > EnergyRequiredToSpawnWorker)
        {
            iCurrentEnergy = 0;
            Vector2 vSpawnPos = myGameActor.GetTargetingPosition() + (Random.insideUnitCircle.normalized * Random.Range(1.0f, 2.5f));
            theGame.SpawnActorPrefab(vSpawnPos, Prefab_WorkerToSpawn);
            theGame.PlaySummoningPoof(vSpawnPos);
            TM_AudioManager.PlayClip(clip_NewWorker);
        }

    }
}
