using UnityEngine;
using System.Collections;

public class BackgroundScript : MonoBehaviour {

	public PlayerScript ps;
	public int bglayer = 0;
	public float offset = 0;
	public Transform cam;
	public bool dreambg = false;

	// Use this for initialization
	void Start () {
		ps = GameObject.FindGameObjectWithTag ("Player").GetComponent<PlayerScript>();
	}
	
	// Update is called once per frame
	void Update () {
		// Update BG art
		if (dreambg) {
			if ((!ps.isdreaming) || (ps.transition)) {
				dreambg = false;
				renderer.material = ps.backgrounds[bglayer];
			}
		} else {
			if ((ps.isdreaming) && (!ps.transition)) {
				dreambg = true;
				renderer.material = ps.backgrounds[(bglayer + 3)];
			}
		}
		// Update BG positions
		float xcalc = cam.position.x;
		switch (bglayer) {
		case 0:
			xcalc /= 1.75F;
			break;
		case 1:
			xcalc /= 1.25F;
			break;
		case 2:
			xcalc /= 1.05F;
			break;
		}
		xcalc += offset;
		if (xcalc < (cam.position.x - 20F)) {
			do {
				xcalc += 35.7F;
			} while (xcalc < (cam.position.x - 24F));
		} else if (xcalc > (cam.position.x + 24F)) {
			do {
				xcalc -= 35.7F;
			} while (xcalc > (cam.position.x + 24F));
		}
		transform.position = new Vector3(xcalc,transform.position.y,transform.position.z);
	}
}
