using UnityEngine;
using System.Collections;

public class s_GameObjectFitScreen : MonoBehaviour
{
	public bool useForground = false;
	
	void Start ()
	{
		//Get all the original data
		Vector3 cameraPos = Camera.main.transform.position;
		Quaternion cameraRotation = Camera.main.transform.rotation;
		Quaternion myRotation = transform.rotation;
		
		//For some reason, it works when they are at 0, 0, 0 and the camera is rotated 90 in x...
		Camera.main.transform.position = Vector3.zero;
		Camera.main.transform.rotation = Quaternion.identity;
		Camera.main.transform.Rotate(90, 0, 0);
		transform.position = Vector3.zero;
		transform.rotation = Quaternion.identity;
		
		//Found out that it doesn't work on orthographic cameras, so switches it just for the scale
		//Will need a secondary camera to render this that is in perspective though
		
		bool orthographic = false;
		if (Camera.main.orthographic)
		{
			orthographic = true;
			Camera.main.orthographic = false;
		}
		
		
		//And only then will the scale work (though x and z are flipped)
		Vector3 newScale = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, -1));
		newScale.x *= -1;
		newScale.z *= -1;
		gameObject.transform.localScale = newScale;
		
		
		//Put them back
		if (orthographic)
			Camera.main.orthographic = true;
		
		
		Camera.main.transform.position = cameraPos;
		Camera.main.transform.rotation = cameraRotation;
		
		if (useForground)
		{
			Camera forground = GameObject.Find("Foreground Camera").camera;
			transform.position = new Vector3(forground.transform.position.x, forground.transform.position.y - 5.0f, forground.transform.position.z);
		}
		else
			transform.position = new Vector3(cameraPos.x, cameraPos.y - 5.0f, cameraPos.z); //5.0f is very important, centers it.
		transform.rotation = myRotation;
	}
}
