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

public class Game : MonoBehaviour {

    public static string configData;
    public List<Player> players;
	public InputField playerNameInput1;
	public InputField playerNameInput2;
	public GameObject coin;
	public AnimationClip coinToss1;
	public AnimationClip coinToss2;

	public string playerName1;
	public string playerName2;

	public Sprite knobIcon;

	int randomNumber;
	bool clickFinish = true;
	bool playFinish = false;
    static public Monster tempMonster;
    static public int pickRound;
	
	PlayerNames playerNames = new PlayerNames();

	Sprite fireIcon;
	Sprite earthIcon;
	Sprite airIcon;
	Sprite waterIcon;


	public List<AudioClip> clips;

    /*void Awake(){
		DontDestroyOnLoad(this);
	}*/

    // Use this for initialization
    IEnumerator Start() {

		fireIcon = (Sprite)Resources.Load<Sprite>("IconFlame");
		airIcon = (Sprite)Resources.Load<Sprite>("IconAir");
		earthIcon = (Sprite)Resources.Load<Sprite>("IconStone");
		waterIcon = (Sprite)Resources.Load<Sprite>("IconWater");

        string filename = "ExternalData/config.json";
        configData = "";
        string prefix = "";

        if (!Application.isWebPlayer)
            prefix = "file://";
        string pathname = prefix + Application.dataPath + "/../" + filename;
        WWW www = new WWW(pathname);
        yield return www;

        configData = www.text;
        GameMaster.configData = configData;
	
        pickRound = 0;
    }
	
	public void Update(){
		if (Application.loadedLevelName == "coinToss") {
			if (coin.GetComponent<Animation> ().IsPlaying ("coinToss1")) {
				Debug.Log ("Animation CoinToss1 is playing");
				playFinish = true;
			} else if (coin.GetComponent<Animation> ().IsPlaying ("coinToss2")) {
				Debug.Log ("Animation CoinToss2 is playing");
				playFinish = true;
			}
		
			if (!coin.GetComponent<Animation> ().IsPlaying ("coinToss1") && !coin.GetComponent<Animation>().IsPlaying("coinToss2") && playFinish) {
				playFinish = false;
				Application.LoadLevel ("createDemon");
			}
		}
	}
	
    public void SetPlayers(){
		playerName1 = playerNameInput1.text;
		playerName2 = playerNameInput2.text;
		 
		if(playerName1 == ""){
			playerName1 = "Player #1";
		}
		
		if(playerName2 == ""){
			playerName2= "Player #2";
		}
		GameMaster.SetPlayersInList(playerName1, playerName2);
		Application.LoadLevel("coinToss");
    }


    public void SetActivePlayer() {
        randomNumber = Random.Range(0, 2);
        GameMaster.activePlayer = randomNumber;
		Debug.Log (randomNumber);

		if (randomNumber == 0) {
			GameMaster.state = false;
		} else {
			GameMaster.state = true;
		}

		if(randomNumber == 0){
			coin.GetComponent<Animation>().Play("coinToss1");
			coin.GetComponent<AudioSource>().Play(5150);
			playFinish = false;
		}else{
			coin.GetComponent<Animation>().Play("coinToss2");
			coin.GetComponent<AudioSource>().Play(5150);
			playFinish = false;
			//TODO: Sound
		}
    }

	public void StartButton(){
		Application.LoadLevel("playerScreen");
	}
	
	public void ExitButton(){
		Application.Quit();
	}




    public void ElementClick(string choosedElement){
		if (clickFinish) {

			if (tempMonster == null) {
				tempMonster = new Monster (GameMaster.players [GameMaster.activePlayer]);
			}

			if (tempMonster.GetElementsCount () < 3) {

				Elements element;
				int elementsCount = tempMonster.GetElementsCount ();
				Image img = GameObject.Find ("element" + elementsCount).GetComponent<Image> ();
			
				switch (choosedElement) {
				case "fire":
					element = Elements.FIRE;
					img.sprite = fireIcon;
					break;

				case "earth":
					element = Elements.EARTH;
					img.sprite = earthIcon;
					break;

				case "air":
					element = Elements.AIR;
					img.sprite = airIcon;
					break;

				case "water":
					element = Elements.WATER;
					img.sprite = waterIcon;
					break;

				default:
					element = Elements.FIRE;
					break;
				}

				tempMonster.AddElement (element);
			}


			if (tempMonster.GetElementsCount () == 3) {
				clickFinish = false;
				GameMaster.players [GameMaster.activePlayer].AddMonster (tempMonster);
				tempMonster = null;
			
				StartCoroutine (Wait ());
			}
			Debug.Log ("Active Player: " + GameMaster.activePlayer);
		}
    }


    public void ChooseInitialMonster(int index) {
        Debug.Log("Pickround" +pickRound);

        GameMaster.players[GameMaster.activePlayer].SetActiveMonster(index);

        pickRound++;
        GameMaster.changeActivePlayer();

		if (LoadPortraits.select1.active == true) {
			LoadPortraits.select1.active = false;
			LoadPortraits.select2.active = true;
		} else {
			LoadPortraits.select1.active = true;
			LoadPortraits.select2.active = false;
		}
		if(pickRound == 1) {
			//GameObject.Find ("selectDemon0").GetComponent<Canvas> ().enabled = !GameMaster.state;
			//GameObject.Find ("selectDemon1").GetComponent<Canvas> ().enabled = GameMaster.state;
		}
        if(pickRound >= 2) {
            Application.LoadLevel("battleScreen");
        }
     
    }
	
	IEnumerator Wait(){

		Debug.Log("Wait-Funktion");
		yield return new WaitForSeconds(1);

		Debug.Log ("Replace icons");
		GameObject.Find("element0").GetComponent<Image>().sprite = knobIcon;
		GameObject.Find("element1").GetComponent<Image>().sprite = knobIcon;
		GameObject.Find("element2").GetComponent<Image>().sprite = knobIcon;
		clickFinish = true;
			
			pickRound++;

            if (pickRound == 1 || pickRound == 3 || pickRound == 5)
            {
                GameMaster.changeActivePlayer();
				GameObject.Find("xplayer1").transform.GetChild(8).gameObject.SetActive(GameMaster.state);
				GameObject.Find("xplayer2").transform.GetChild(8).gameObject.SetActive(!GameMaster.state);
            }
        

        if (pickRound == 6) {
            Application.LoadLevel("selectDemon");
		}
	}

	void OnLevelWasLoaded(int level) {
		if (level == 6) {
			GameObject.Find ("selectDemon0/Titel").GetComponent<Text> ().text = GameMaster.players [0].GetName ();
			GameObject.Find ("selectDemon1/Titel").GetComponent<Text> ().text = GameMaster.players [1].GetName ();
			//GameObject.Find ("selectDemon0").GetComponent<Canvas> ().enabled = !GameMaster.state;
			//GameObject.Find ("selectDemon1").GetComponent<Canvas> ().enabled = GameMaster.state;
		} else if (level == 5) {
			GameObject.Find ("Canvas/Titel").GetComponent<Text> ().text = GameMaster.players [GameMaster.winner].GetName () + " has won!";
		}
	}

	public void BattleChangeClick(int newActiveMonster) {

		GameMaster.players [GameMaster.activePlayer].SetActiveMonster (newActiveMonster);
		Component battleComponent = GameObject.Find ("Skripte").GetComponent<Battle> ();

		//GameObject.Find ("MonsterContainer" + GameMaster.activePlayer).GetComponent<DemonControl>().delayDeath ();

		Component.Destroy (battleComponent);

		GameObject.Find ("selectOverlay" + GameMaster.activePlayer).GetComponent<Canvas> ().enabled = false;

		GameObject.Find ("Skripte").GetComponent<PokaemonCreation>().createPrefab(GameMaster.activePlayer);
		GameObject.Find ("Skripte").AddComponent<Battle> ();
		GameObject.Find ("Skripte").GetComponent<BattleCanvasScript> ().changeMaxHp (GameMaster.activePlayer);
	}
}
