using System.Collections;
using UnityEngine;
using matnesis.TeaTime;

public class SideScroll : MonoBehaviour 
{
	public Transform target;
	public float camHSpeed = 1;
	public float camVSpeed = 2;
	public PlayerMovement movement;
	public float xMinLimit = 0.1f;
	public float xMaxLimit = 0.7f;

	public bool inTransition;

	public Vector3 screenLimits;
	private TeaTime camTranslation;
	private Vector2 offset;

	// Use this for initialization
	void Start () 
	{
		offset = new Vector2(target.position.x - transform.position.x,
				target.position.y - transform.position.y);

		if(movement == null) { movement = FindObjectOfType<PlayerMovement> (); }

		screenLimits = Camera.main.WorldToViewportPoint (movement.transform.position);
	}

	void FixedUpdate ()
	{
		screenLimits = Camera.main.WorldToViewportPoint (movement.transform.position);

		movement.forward = screenLimits.x < xMinLimit;
	
		if(inTransition)
		{
			return;
		}

		Vector3 nextPos = transform.position;
		nextPos.y = Mathf.Lerp(nextPos.y, target.position.y - offset.y, Easef.EaseIn(camVSpeed * Time.fixedDeltaTime));
		transform.position = nextPos;

		if(screenLimits.x >= xMaxLimit)
		{
			transform.Translate (camHSpeed * Time.fixedDeltaTime, 0, 0);
		}
	}

	public void StartTransitionToPlayer ()
	{
		inTransition = true;
		this.tt ("MoveToPlayer").Loop (2, (ttHandler t) => 
			{
				Vector3 newPos = transform.position;
				newPos.x = Mathf.Lerp(newPos.x, movement.transform.position.x, Easef.EaseOut(t.t));
				transform.position = newPos;
			}).Add(() => 
				{
					inTransition = false;
				}).Immutable();
	}
}
