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

public class LDSpawnerComponent : MonoBehaviour
{
    [Header("Just Spawner Things <3")]
    public LDGameActor myOwningActor;
    public GameObject Prefab_CreatureToSpawn;
    public float SecondsUntilReady;
    public TM_SpriteAnimator myAnimComponent;
    public bool AnchorToTheCreatureThatSpawnedMe;
    public bool SpawnWhenPlayerIsNear;
    private bool bReadyToSpawn;
    public AudioClip clip_OnSpawn;

    private float fSpawnLife;
    private GameManager theGame;

    protected virtual void Update()
    {

        fSpawnLife += Time.deltaTime;

        float fRatio = fSpawnLife / SecondsUntilReady;
        if (fRatio < 0.5f)
        {
            myAnimComponent.StartIfNotRunning("empty");
        }
        else if (fRatio < 1.0f)
        {
            myAnimComponent.StartIfNotRunning("growing");
        }
        else
        {
            myAnimComponent.StartIfNotRunning("ready");
            bReadyToSpawn = true;
        }

    }


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

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

    protected bool OnHitObject(GameObject hitObject)
    {
        theGame = GameManager.GetGame();

        //we're in the same layer, let's sort of move away from each other
        if (hitObject == theGame.thePlayer.gameObject && SpawnWhenPlayerIsNear &&  bReadyToSpawn)
        {
            SpawnMyCreature( hitObject.GetComponent<LDGameActor>());
        }

        return true;
    }

    void SpawnMyCreature(LDGameActor creatureWhoWokeMeUp)
    {
        LDGameActor ga = theGame.SpawnActorPrefab(myOwningActor.GetTargetingPosition(), Prefab_CreatureToSpawn);

        if (AnchorToTheCreatureThatSpawnedMe)
        {
            ga.SetAnchorActor(creatureWhoWokeMeUp);
        }

        bReadyToSpawn = false;
        fSpawnLife = 0f;

        TM_AudioManager.PlayClip(clip_OnSpawn);

    }
}
