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

public enum CameraMode
{
	world,
	level
}

public class CameraController : MonoBehaviour {

	public float switchSpeed = 5f;
	
	[Header("Level lookout position ref")]
	public Transform levelCameraTransform;
	
	public Transform playerTransform;
	public float followPlayerSpeed = 0.5f;
	
	Vector3 worldCameraLocalPos;
	Quaternion worldCameraLocalRot;

	Vector3 destinationLocalPos;
	Quaternion destinationLocalRot;
	
	Vector3 playerInitialPosOnLevelViewOpen;
	
	CameraMode cameraMode;
	

	void Awake () {
		// initial position is considered to be world view
		cameraMode = CameraMode.world;
		worldCameraLocalPos = transform.localPosition;
		worldCameraLocalRot = transform.localRotation;
		// with current pos and rot as default destination
		destinationLocalPos = worldCameraLocalPos;
		destinationLocalRot = worldCameraLocalRot;
	}
	
	
	
	void Update() {
		
		if (cameraMode == CameraMode.level)
		{
			Vector3 v = transform.localPosition;
			v.x = playerTransform.position.x;
			v.y = playerTransform.position.y;
			transform.localPosition = Vector3.Lerp(transform.localPosition, v, Time.unscaledDeltaTime * followPlayerSpeed);
		}
	}
	
	
	
	public void SwitchCameraMode(CameraMode newMode)
	{
		switch(newMode)
		{
			case CameraMode.world:
				destinationLocalPos = worldCameraLocalPos;
				destinationLocalRot = worldCameraLocalRot;
				cameraMode = newMode;
				break;
			case CameraMode.level:
				destinationLocalPos = levelCameraTransform.position;
				destinationLocalPos.x = playerTransform.position.x;
				destinationLocalPos.y = playerTransform.position.y;
				destinationLocalRot = levelCameraTransform.localRotation;
				playerInitialPosOnLevelViewOpen = playerTransform.position;
				cameraMode = newMode;
				break;
		}
		
		StopAllCoroutines();
		StartCoroutine(UpdateCameraPosCoroutine());
	}
	
	
	IEnumerator UpdateCameraPosCoroutine() {
		
		if (transform.localPosition == destinationLocalPos &&
			transform.localRotation == destinationLocalRot)
			yield break;
		
		for( float t = 0; t <= 1; t += Time.unscaledDeltaTime * switchSpeed)
		{
			transform.localPosition =
				Vector3.Lerp(transform.localPosition, destinationLocalPos, t);
			
			transform.localRotation =
				Quaternion.Lerp(transform.localRotation, destinationLocalRot, t);
			
			yield return null;
		}
		
		transform.localPosition = destinationLocalPos;
		transform.localRotation = destinationLocalRot;
	}
}
