using UnityEngine;
using System.Collections;

[ExecuteInEditMode]
[RequireComponent(typeof(Camera))] 

public class PerPixelCamera : MonoBehaviour {
	
	public static Camera mainCamera;
	
	const int MAX_CANVAS_HEIGHT = 120; // 120x160 pixel canvas in 4x3 or 120x(>160)
	int canvasPixelSize;
	Vector2 CanvasSize;
	//TODO
	int currentScreenHeight;
	
		
	[SerializeField] private Vector3 position = new Vector3(0, 0, -30);
	[SerializeField] private Vector3 eulerAngles = new Vector3(0, 0, 0);
	
	void RecalculateCanvasPixelSize(){
		canvasPixelSize = Screen.height / MAX_CANVAS_HEIGHT;
		CanvasSize = new Vector2((float)Screen.width / (float)canvasPixelSize, (float)Screen.height / (float)canvasPixelSize);
		currentScreenHeight = Screen.height;
		mainCamera.orthographicSize = CanvasSize.y / 20f;
		Control.RecalculateScreenAspect(mainCamera.orthographicSize);
//		Debug.Log(Screen.width.ToString() + " " + Screen.height.ToString());
//		Debug.Log(CanvasSize.ToString());
	}
	
	void Awake () {
		mainCamera = this.camera;
		transform.localPosition = position;
		transform.localRotation = Quaternion.Euler(eulerAngles);
		
		RecalculateCanvasPixelSize();
	}
	
	void Start () {
		RecalculateCanvasPixelSize();
	}
	
	void Update () {
		if (currentScreenHeight != Screen.height){
			RecalculateCanvasPixelSize();
		}
	}
}
