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

public class Bullet : MonoBehaviour {

	//Layers
	string layerName;
	Dictionary<string, GameObject> layers = new Dictionary<string, GameObject>();

	//Movement
	float layerWidth = 4.8f;
	float moveSpeed = 0.75f;
	public float localX;
	public float localZ;

	//Textures
	public Material redTexture;
	public Material blueTexture;
	public Material greenTexture;
	public Material yellowTexture;
	Dictionary<string, Material> textures = new Dictionary<string, Material>();

	//Scripts
	GameObject scripts;
	GameObject player;

	// Use this for initialization
	void Start () {
		//Set layers
		layers.Add ("red", GameObject.Find ("RedLayer"));
		layers.Add ("blue", GameObject.Find ("BlueLayer"));
		layers.Add ("green", GameObject.Find ("GreenLayer"));
		layers.Add ("yellow", GameObject.Find ("YellowLayer"));
		scripts = GameObject.Find("ScriptContainer");
		layerName = scripts.GetComponent<LayerManager>().getTopLayerName();

		//Player
		player = GameObject.Find ("Player");

		//Materials
		textures.Add("red", redTexture);
		textures.Add("blue", blueTexture);
		textures.Add("green", greenTexture);
		textures.Add("yellow", yellowTexture);
		this.renderer.material = textures[player.GetComponent<PlayerMovement>().getLayerName()];
		GetComponent<TrailRenderer>().material = textures[player.GetComponent<PlayerMovement>().getLayerName()];

		//Start it at its correct position
		moveBullet ();
	}
	
	// Update is called once per frame
	void Update () {
	
		//Move player on plane
		localX += transform.up.x * moveSpeed;
		localZ += transform.up.z * moveSpeed;

		//Delete me when I leave the bounds
		if(localX < -layerWidth || localX > layerWidth || localZ < -layerWidth || localZ > layerWidth){
			deleteMe ();
		}
		
		//Move based on the layer's position and local position
		moveBullet ();
	}

	void OnCollisionEnter(Collision collision){
		if(collision.gameObject.tag == "Enemy"){
			if(collision.gameObject.GetComponent<Enemy>().getColor () == player.GetComponent<PlayerMovement>().getLayerName ()){
				deleteMe ();
				teleportPlayer(collision.gameObject.transform.position);

				//Kill the enemy and make it explode
				collision.gameObject.GetComponent<Enemy>().killMe (true);
			}
			else{
				audio.Play ();
				deleteMe ();
			}
		}
	}

	void deleteMe(){
		GameObject.Find ("Player").GetComponent<PlayerMovement>().setBulletExists(false);
		Destroy(this.gameObject);
	}

	void teleportPlayer(Vector3 newSpot){
		GameObject.Find ("Player").GetComponent<PlayerMovement>().teleportTo(newSpot, layerName);
	}

	void moveBullet(){
		transform.position = new Vector3(layers[layerName].transform.position.x + localX,
		                                 layers[layerName].transform.position.y,
		                                 layers[layerName].transform.position.z + localZ);
	}
}
