using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System;
using UnityEngine.Audio;
public class DrMarioExample : MonoBehaviour {

	public Material materialToUse;
	public GameObject SpriteParent; 
    public Vector3 FaceLeft;
    public Vector3 FaceRight;
    public int adjx = 0;
    public int adjy = 0;
    public Text DEBUGTEXT;
    public int MemOffset = 2;
    //public GameObject PyFoot;
	public List<string> Animations = new List<String>(); 
    public int timer = 26;
    public Vector3 Hidden;
    public Vector3 MarioLocation;
    public Vector3 MarioOffset;
    public GameObject MarioOBJ;
	public List<GameObject> Mario = new List<GameObject>();
    public string persistentDataPath;
    public string currentRomName;
    public AudioClip splat;
    public AudioSource Audio;
    // Use this for initialization
    public IEnumerator OnScriptLoaded() {
		SpriteParent = GameObject.Find("Sprites");
		Hidden = new Vector3(-2000, 0, 0);
        FaceLeft = new Vector3(-200, 0, 0);
        FaceRight = new Vector3(200, 0, 0);
        DEBUGTEXT = GameObject.Find("DEBUGTEXT").GetComponent<Text>();
        MarioLocation = new Vector3(0, 0, 0);
        persistentDataPath = Application.dataPath + "/../";
        currentRomName = RxScriptInit.currentRomName;
        MarioOBJ = GameObject.Instantiate(Resources.Load("OBJPrefab"), new Vector3(0, 0, 0), Quaternion.identity) as GameObject;
		if (File.Exists(persistentDataPath + "/Enhancements/" + currentRomName + "/-MyPackage-/DrMarioModel/Mario.obj") == true){
			UnityEngine.Debug.Log(persistentDataPath + "/Enhancements/" + currentRomName + "/-MyPackage-/DrMarioModel/Mario.obj EXISTS!");
		}
        MarioOBJ.SendMessage("LoadOBJ", "file:///" + persistentDataPath + "/Enhancements/" + currentRomName + "/-MyPackage-/DrMarioModel/Mario.obj");
        MarioOBJ.name = "MarioOBJ";
        MarioOffset = new Vector3(0,-26,0);
        yield return new WaitForSeconds(2.75f);
        foreach (Transform bt in MarioOBJ.transform){
            if (bt.gameObject.GetComponent<Renderer>() != null){
				Material[] myMaterials;
                myMaterials = bt.gameObject.GetComponent<Renderer>().materials;
            bt.gameObject.GetComponent<Renderer>().enabled = true;
			foreach (Material m in myMaterials){
			m.shader = Shader.Find("Unlit/Transparent Cutout");
			}
            bt.gameObject.transform.localPosition = Vector3.zero;
			Mario.Add(bt.gameObject);
            }
        }
        //WWW www = new WWW("file:///" + persistentDataPath + "/Enhancements/" + currentRomName + "/-MyPackage-/splat.ogg");
        //if (File.Exists(persistentDataPath + "/Enhancements/" + currentRomName + "/-MyPackage-/splat.ogg") == true)
        //{
        //    UnityEngine.Debug.Log(persistentDataPath + "/Enhancements/" + currentRomName + "/-MyPackage-/splat.ogg" + " Exists!");
        //} else
        //{
        //    UnityEngine.Debug.Log(persistentDataPath + "/Enhancements/" + currentRomName + "/-MyPackage-/splat.ogg" + " DOES NOT EXIST!!!!!");
        //}
        //yield return www;
        //splat = www.GetAudioClip(false);
        //PyFoot = GameObject.Instantiate(Resources.Load("Quad", typeof(GameObject))) as GameObject;
        //PyFoot.GetComponent<Renderer>().enabled = false;
        //PyFoot.transform.position = Hidden;
        //Audio = PyFoot.AddComponent<AudioSource>();
        //Audio.playOnAwake = false;
        //Audio.clip = splat;

        
        //FileStream fs = new FileStream(persistentDataPath + "/Enhancements/" + currentRomName + "/-MyPackage-/PyFoot.png", FileMode.Open, FileAccess.Read);
        //byte[] imageData = new byte[fs.Length];
        //fs.Read(imageData, 0, (int)fs.Length);

        //PyFootT2D = new Texture2D(32, 32, TextureFormat.ARGB32, false);

        //PyFootT2D.LoadImage(imageData);
        //PyFoot.GetComponent<Renderer>().material.mainTexture = PyFootT2D;
        //PyFoot.transform.localScale = new Vector3(30f, 30f, 30.0f);
        //PyFoot.GetComponnt
        //Debug.Log("Please see 'MontyPython Example.cs' for Example!");
    }

    public void Update()
    {
		
        if (MyNes.NesEmu.mem_wram != null){
			/* bool addnew = true;
			string val = MyNes.NesEmu.mem_wram[2].ToString("X2");
			foreach (string s in Animations.ToArray()){
if (s == val){
	addnew = false;
}
			}
			if (addnew == true){
	File.AppendAllText(persistentDataPath + "/Enhancements/" + currentRomName + "/-MyPackage-/Mario/Animations.txt", "if (MyNes.NesEmu.mem_wram[2].ToString(\"X2\") == \"" + val + "\")" + Environment.NewLine + "{" + Environment.NewLine + "foreach (GameObject go in Mario){" + Environment.NewLine + "						if (go.name.Contains(\"" + val + "\") && go.GetComponent<Renderer>() != null){" + Environment.NewLine + "							go.GetComponent<Renderer>().enabled = true;" + Environment.NewLine + "						} else {" + Environment.NewLine + "							go.GetComponent<Renderer>().enabled = false;" + Environment.NewLine + "						}" + Environment.NewLine + "					}" + Environment.NewLine + "}" + Environment.NewLine);	
	Animations.Add(val);
	
			} */
		if (Input.GetKeyDown(KeyCode.I) == true){
				MemOffset--;
				MemOffset = Mathf.Clamp(MemOffset, 0, MyNes.NesEmu.mem_wram.Length);
			}
			if (Input.GetKeyDown(KeyCode.O) == true){
				MemOffset++;
				MemOffset = Mathf.Clamp(MemOffset, 0, MyNes.NesEmu.mem_wram.Length);
			}
			//DEBUGTEXT.text = "MemOffset " + MemOffset.ToString("X2") + " : " + MyNes.NesEmu.mem_wram[MemOffset].ToString("X2");
			int x = (int)(((int)MyNes.NesEmu.mem_wram[941])/8);
			int y = (int)-(((int)MyNes.NesEmu.mem_wram[206])/8);
			if (MarioOBJ != null){
				MarioLocation = new Vector3(x+1, y, 0);
				//MarioLocation = new Vector3(8, -12, 0);
				MarioOBJ.transform.position = MarioLocation;
				
				foreach (Transform st in MarioOBJ.transform){
					st.gameObject.transform.localPosition = MarioOffset;
				}
                //foreach (Renderer r in SpriteParent.transform){

                //}
                /* if (MyNes.NesEmu.mem_wram[1878] == 0){
					foreach (GameObject go in Mario){
						if (go.name.Contains("Small") && go.GetComponent<Renderer>() != null){
							go.GetComponent<Renderer>().enabled = true;
						} else {
							go.GetComponent<Renderer>().enabled = false;
						}
					}
				}
        
				if (MyNes.NesEmu.mem_wram[1878] == 1){  
					foreach (GameObject go in Mario){
						if (go.name.Contains("Big") && go.GetComponent<Renderer>() != null){
							go.GetComponent<Renderer>().enabled = true;
						} else {
							go.GetComponent<Renderer>().enabled = false;
						}
					}
				} */
                if (MyNes.NesEmu.mem_wram[1878] == 0 || MyNes.NesEmu.mem_wram[1878] == 1)
                {
                    foreach (GameObject go in Mario)
                    {


                        go.GetComponent<Renderer>().enabled = false;
                    }
                }
                else
                {
                    if (MyNes.NesEmu.mem_wram[1749].ToString("X2") == "C8")
                    {
                        foreach (GameObject go in Mario)
                        {
                            if (go.name.Contains("StandStillBig") && go.GetComponent<Renderer>() != null)
                            {
                                go.GetComponent<Renderer>().enabled = true;
                            }
                            else
                            {
                                go.GetComponent<Renderer>().enabled = false;
                            }
                        }
                    }
                    if (MyNes.NesEmu.mem_wram[1749].ToString("X2") == "00")
                    {
                        foreach (GameObject go in Mario)
                        {
                            if (go.name.Contains("Run01Big") && go.GetComponent<Renderer>() != null)
                            {
                                go.GetComponent<Renderer>().enabled = true;
                            }
                            else
                            {
                                go.GetComponent<Renderer>().enabled = false;
                            }
                        }
                    }
                    if (MyNes.NesEmu.mem_wram[1749].ToString("X2") == "10")
                    {
                        foreach (GameObject go in Mario)
                        {
                            if (go.name.Contains("Run02Big") && go.GetComponent<Renderer>() != null)
                            {
                                go.GetComponent<Renderer>().enabled = true;
                            }
                            else
                            {
                                go.GetComponent<Renderer>().enabled = false;
                            }
                        }
                    }
                    if (MyNes.NesEmu.mem_wram[1749].ToString("X2") == "20")
                    {
                        foreach (GameObject go in Mario)
                        {
                            if (go.name.Contains("JumpBig") && go.GetComponent<Renderer>() != null)
                            {
                                go.GetComponent<Renderer>().enabled = true;
                            }
                            else
                            {
                                go.GetComponent<Renderer>().enabled = false;
                            }
                        }
                    }
                    if (MyNes.NesEmu.mem_wram[1749].ToString("X2") == "50")
                    {
                        foreach (GameObject go in Mario)
                        {
                            if (go.name.Contains("CrouchBig") && go.GetComponent<Renderer>() != null)
                            {
                                go.GetComponent<Renderer>().enabled = true;
                            }
                            else
                            {
                                go.GetComponent<Renderer>().enabled = false;
                            }
                        }
                    }
                }
				if (MyNes.NesEmu.mem_wram[51] == 1){
					Vector3 targetPostition = new Vector3(MarioLocation.x - 1000, 
                                        MarioLocation.y, 
                                        MarioLocation.z);
					MarioOBJ.transform.LookAt(targetPostition);
					
				}
				if (MyNes.NesEmu.mem_wram[51] == 2){
					Vector3 targetPostition = new Vector3(MarioLocation.x + 1000, 
                                        MarioLocation.y, 
                                        MarioLocation.z);    
					MarioOBJ.transform.LookAt(targetPostition);
					
				}
        
				if (MyNes.NesEmu.mem_wram[51] == 0){
					foreach (GameObject go in Mario){
						if (go.GetComponent<Renderer>() != null){
							go.GetComponent<Renderer>().enabled = false;
						}
					}
				}
				timer++;
				if (timer > int.MaxValue - 300)
				{
					timer = 61;
				}
			} else {
				UnityEngine.Debug.Log("MarioOBJ == null");
			}
		}
    }

}