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

public class AntiSpyCam : Enemy
{
    // Ray sources
    public Light m_Light;
    public Texture m_GreenLight;
    public Texture m_RedLight;
    public List<Transform> RaySources;
    private Transform[] m_RaySources;
    private Ray[] m_View;

    // Routine
    private EnemyRoutine m_Routine;

    protected override void Start()
    {
        base.Start();

        if (RaySources != null && RaySources.Count > 0)
        {
            m_RaySources = RaySources.ToArray();
        }
        m_View = new Ray[m_RaySources.Length];

        for(int i = 0; i<m_View.Length; ++i)
        {
            m_View[i] = new Ray();
        }

        m_Routine = GetComponent<EnemyRoutine>();
    }

    // Update is called once per frame
    public override void UpdateCharacter()
    {
        RaycastHit hitInfo;
        foreach (Ray ray in m_View)
        {
            //if (Physics.Raycast(ray, out hitInfo, Mathf.Infinity, LayersUtils.HeroLayer))
            if (Physics.Raycast(ray, out hitInfo))
            {
                //Debug.Log("Test : " + hitInfo.transform.name);
                if (hitInfo.transform.gameObject.layer == LayersUtils.HeroLayerMask)
                {
                    // Stop its routine
                    m_Routine.SetEnable(false);
                    // Light is red !
                    m_CharacterModel.renderer.materials[2].SetTexture("_MainTex", m_RedLight);
                    m_Light.color = Color.red;
                    // Inform the GameManager
                    GameManager.Instance.Lost();
                }
            }
        }

        // Define rays
        for (int i = 0; i < m_View.Length; ++i)
        {
            m_View[i].origin = m_RaySources[i].position;
            m_View[i].direction = m_RaySources[i].up;

            Debug.DrawRay(m_View[i].origin, m_View[i].direction, Color.red, 0.1f);
        }
    }

    public override void ReInit()
    {
        m_Light.color = Color.green;
        m_CharacterModel.renderer.materials[2].SetTexture("_MainTex", m_GreenLight);
        m_Routine.SetEnable(true);
    }

    public override void Spawn(Vector3 position)
    {
    }
}