using UnityEngine;
using System.Collections;

public enum SwitchType
{
    TOUCH,
    JUMP,
    BULLET,
    STOMP,
}

public class Switch : MonoBehaviour
{
    public Switcharoo switcharoo;
    public SwitchType type = SwitchType.TOUCH;

    public Transform state_normal = null;
    public Transform state_pressed = null;
    
    private bool isTriggered = false;

    public void Awake()
    {
        state_normal.gameObject.SetActive(true);
        state_pressed.gameObject.SetActive(false);
    }

    public void OnDrawGizmos()
    {
        Gizmos.color = Color.green;
        if (switcharoo != null)
        {
            Gizmos.DrawLine(transform.position, switcharoo.transform.position);
        }
    }

    ContactPoint2D[] collisionContacts;
    public void OnCollisionEnter2D(Collision2D collision)
    {
        if (isTriggered) return;

        BulletController bullet = collision.collider.GetComponentInParent<BulletController>();
        EntityController entity = collision.collider.GetComponentInParent<EntityController>();

        if (bullet != null && type == SwitchType.BULLET)
        {
            Trigger(null);
            return;
        }

        if (entity != null)
        {
            if (type == SwitchType.TOUCH)
            {
                Trigger(entity);
                return;
            }
            else if (type == SwitchType.STOMP && entity.isStomping)
            {
                Trigger(entity);
                return;
            }
            else if (type == SwitchType.JUMP && entity.isJumping)
            {
                if (collisionContacts == null) collisionContacts = new ContactPoint2D[10];
                for (int i = 0; i < collisionContacts.Length; i++)
                {
                    collisionContacts[i] = new ContactPoint2D();
                }
                    
                if (collision.GetContacts(collisionContacts) > 0)
                {
                    for (int i = 0; i < collisionContacts.Length; i++)
                    {
                        ContactPoint2D contact = collisionContacts[i];
                        if (!contact.enabled) continue;

                        float downAngle = Vector2.Angle(contact.normal, Vector2.up);
                        if (downAngle < 25.0f)
                        {
                            Trigger(entity);
                            return;
                        }
                    }
                }
            }
        }
    }

    public void Trigger(EntityController entity)
    {
        if (isTriggered) return;
        isTriggered = true;

        if (switcharoo != null)
        {
            switcharoo.Trigger(entity);
        }

        Collider c = GetComponentInChildren<Collider>();
        if (c != null)
        {
            c.enabled = false;
        }

        state_normal.gameObject.SetActive(false);
        state_pressed.gameObject.SetActive(true);
    }
}

