using UnityEngine;
using System.Collections;

public class CameraScript : MonoBehaviour {

    public GameObject player;
    public GameObject gameManager;
    public float rotationSpeed;
    public float startRotation;
    public float endRotation;
    float currentRotation;

    public AudioSource alarm;

    bool rotateForward;
    bool alarmPlay;
    bool inSight;
	// Use this for initialization
	void Start () {
        player = GameObject.FindGameObjectWithTag("Player");
        inSight = false;
        rotateForward = true;
        transform.rotation = Quaternion.AngleAxis(startRotation, Vector3.forward);
        currentRotation = startRotation;
        alarmPlay = false;
	}
	
	// Update is called once per frame
    void Update()
    {
        if(currentRotation > endRotation){
            rotateForward = false;
        }else if (currentRotation < startRotation) {
            rotateForward = true;
        }

        if (currentRotation <= endRotation && rotateForward) { 
            currentRotation += rotationSpeed;
            transform.rotation = Quaternion.AngleAxis(currentRotation, Vector3.forward);
        }else if(currentRotation >= startRotation && !rotateForward){
            currentRotation -= rotationSpeed;
        }

         transform.rotation = Quaternion.AngleAxis(currentRotation, Vector3.forward);
       
        if (inSight)
        {
            
            gameManager.gameObject.SendMessage("PlayerSeenByCamera");
        }
    }

    void OnTriggerStay2D(Collider2D other)
    {
        if (other.gameObject == player)
        {
            if (!alarmPlay)
            {
                playAlarm();
            }
            else
            {
                Invoke("resetAlarm", 5);
            }
            inSight = true;
        }
    }
    void OnTriggerExit2D(Collider2D other)
    {
        inSight = false;
    }

    void playAlarm()
    {
        alarmPlay = true;
        alarm.Play();

    }

    void resetAlarm()
    {
        alarmPlay = false;
    }
}
