using UnityEngine;
using System.Collections;

public class FollowCamera : MonoBehaviour {

    [SerializeField] Transform m_followTransform;
    [SerializeField] Vector3 m_offset;
    [SerializeField] float m_maxSpeed = 10.0f;

    float m_shakeDuration;
    float m_shakeIntensity;

    Vector3 m_lerpOffset;


    public void SetFollowTransform(Transform follow)
    {
        m_followTransform = follow;
    }

    public void Shake(float duration, float intensity)
    {
        m_shakeDuration = duration;
        m_shakeIntensity = intensity;
    }

    void Awake() 
    {
        //
    }

    void Start()
	{
    	UpdatePosition(true);
    	
    }

	void Update() 
    {
    	UpdatePosition(false);
	}

	void UpdatePosition( bool snap )
	{
        Vector3 cameraPosition = transform.position;

        if (m_followTransform)
        {
            Vector3 targetOffset;
            Vector3 offset = m_offset;
            offset.Scale(m_followTransform.lossyScale);
            targetOffset = m_followTransform.rotation * offset;

            m_lerpOffset = Vector3.Lerp(m_lerpOffset, targetOffset, 15.0f * Time.deltaTime);

            Vector3 followPosition = m_followTransform.position;

            BodyBlock[] bodyBlocks = m_followTransform.GetComponentsInChildren<BodyBlock>();
            if (bodyBlocks.Length > 0)
            {
                Vector3[] positions = new Vector3[bodyBlocks.Length];
                for (int i = 0; i < positions.Length; i++)
                {
                    positions[i] = bodyBlocks[i].transform.position;
                }

                followPosition = Utils.FindCenter(positions);                
            }

			if ( snap )
                cameraPosition = followPosition + targetOffset;
			else 
                cameraPosition = Vector3.Lerp(cameraPosition, followPosition + m_lerpOffset, m_maxSpeed * Time.deltaTime) ;
        }

		if (m_shakeDuration > 0.0f)
        {
            m_shakeDuration -= Time.deltaTime;

            Vector3 shakeVector = new Vector3(Random.Range(-1.0f, 1.0f), Random.Range(-1.0f, 1.0f));
            shakeVector.Normalize();
            shakeVector *= m_shakeIntensity;

            cameraPosition += shakeVector;
        }

        transform.position = cameraPosition;
	}
}
