using UnityEngine;
using System.Collections;

public enum DoorStates
{
    closed_empty,
    closed_player_within,
    open,
    MAX
}

public class Door : MonoBehaviour
{

    public Sprite closedSprite;
    public Sprite openSprite;
    protected SpriteRenderer m_SpriteRenderer;

    private DoorStates currentDoorState;
    private float fTimeUntilClose;

    public GameObject prefab_enemyToSpawn;
    public int NumberOfSpawns;
    private int iRemainingSpawns;
    private float fCheckSpawnTimer;

    private BaseMans playerScript;

    // Use this for initialization
    private void Start()
    {
        m_SpriteRenderer = GetComponent<SpriteRenderer>();
        iRemainingSpawns = NumberOfSpawns;
        fCheckSpawnTimer = 0.8f + 1.5f * Random.value;
        currentDoorState = DoorStates.closed_empty;
    }

    // Update is called once per frame
    private void Update()
    {
        if (currentDoorState == DoorStates.open)
        {
            fTimeUntilClose -= Time.smoothDeltaTime;
            if( fTimeUntilClose <= 0.0f )
                CloseDoor();
        }

        if (playerScript == null && !GetPlayerScript())
        {
            return;
        }

        float fDistanceToPlayer = transform.position.x - playerScript.transform.position.x;

        if (Mathf.Abs(fDistanceToPlayer) > 8.0f)
            return;

        //Maybe spawn baddie?
        if (iRemainingSpawns > 0 )
        {
            if (fCheckSpawnTimer > 0.0f)
                fCheckSpawnTimer -= Time.smoothDeltaTime;

            if (fCheckSpawnTimer <= 0.0f)
            {
                if (Random.value <= 0.2f)
                {
                    iRemainingSpawns--;
                    OpenDoor();
                    GameObject newGo = GameObject.Instantiate(prefab_enemyToSpawn);
                    newGo.transform.position = transform.position;

                    BaseEnemy badmans = newGo.GetComponent<BaseEnemy>();
                    badmans.currentAiEnemyBehaviorState = AIEnemyBehaviorState.bounce_from_player_impact;
                    badmans.fStunTimer = 0.25f;

                }

                fCheckSpawnTimer = 0.8f + 1.5f*Random.value;
            }
        }

    }

    bool GetPlayerScript()
    {
        GameObject go = GameObject.Find("PlayerMans");
        if (go != null)
        {
            playerScript = go.GetComponent<PlayerMovement>();
        }

        return playerScript != null;
    }

    private void OpenDoor()
    {
        m_SpriteRenderer.sprite = openSprite;
        fTimeUntilClose = 0.5f;
        currentDoorState = DoorStates.open;
    }

    private void CloseDoor()
    {
        m_SpriteRenderer.sprite = closedSprite;
        currentDoorState = DoorStates.closed_empty;
    }

}
