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

[RequireComponent(typeof(Camera))]
public class CameraControl : MonoBehaviour {

	public float minOrthoSize = 5.0f;
	public float maxOrthoSize = 28.0f;

	public float flexOrthoSize = 2.5f;
	public float flexOrthoSpeed = 2.8f;

	public Vector2 boundPosition;
	public Vector2 boundSize;

	private Camera _camera;

	private Vector2 size;

	void Start () {
		_camera = GetComponent<Camera>();

		size = new Vector2(Screen.width/2, Screen.height/2);
	}

	void LateUpdate () {
		ClampOrthographicSize();
		ClampPosition();
	}

	void ClampOrthographicSize() {
		_camera.orthographicSize = Mathf.Clamp(_camera.orthographicSize, minOrthoSize - flexOrthoSize, maxOrthoSize + flexOrthoSize);

		if (_camera.orthographicSize < minOrthoSize) {
			_camera.orthographicSize = Mathf.Lerp(_camera.orthographicSize, minOrthoSize, flexOrthoSpeed * Time.deltaTime);
		} else if (maxOrthoSize < _camera.orthographicSize) {
			_camera.orthographicSize = Mathf.Lerp(_camera.orthographicSize, maxOrthoSize, flexOrthoSpeed * Time.deltaTime);
		}
	}

	void ClampPosition() {
		Vector2 vec = _camera.ScreenToWorldPoint(size) - _camera.ScreenToWorldPoint(Vector2.zero);

		float maxX = boundPosition.x + boundSize.x - vec.x;
		float minX = boundPosition.x - boundSize.x + vec.x;
		float maxY = boundPosition.y + boundSize.y - vec.y;
		float minY = boundPosition.y - boundSize.y + vec.y;

		float x = Mathf.Clamp(_camera.transform.position.x, minX, maxX);
		float y = Mathf.Clamp(_camera.transform.position.y, minY, maxY);
		float z = _camera.transform.position.z;

		_camera.transform.position = new Vector3(x, y, z);
	}
}
