/*
         * public static void AddConditionalCallback(object obj)
         * {
         *  Debug.Log("Add conditional.");
         *
         * }*/


        /// <summary>
        /// adds a state.
        /// </summary>
        /// <param name="obj"></param>
        public static void CreateStateContextCallback(object obj)
        {
            //make the passed object to a string
            //string clb = obj.ToString();
            editorDisplayWindowsState.menuData menuData = (editorDisplayWindowsState.menuData)obj;


            if (/*clb.Equals("addState") && */ GameObject != null)
            {
                SaveAllVisualStateMetaData();

                if (StateList.Count == 0)
                {
                    Debug.LogError("StateList is Empty so you can't create a state.");
                    return;
                }
                //string stateName = "aMech" + GameObject.name + "State" + utlDataAndFile.GetCode(StateList.Count);

                int    codeIndex = StateList.Count;
                string stateName = "aMech" + GameObject.name + "State" + utlDataAndFile.GetCode(codeIndex);
                while (!CreateAndAddStateCodeToProject(GameObject, stateName, menuData.m_FileAndPath, menuData.m_ReplaceName, false))
                {
                    codeIndex += 1;
                    stateName  = "aMech" + GameObject.name + "State" + utlDataAndFile.GetCode(codeIndex);
                    //sanity check
                    if (codeIndex > 10000)
                    {
                        return;
                    }
                }


                string fileAndPath = "";
                fileAndPath = utlDataAndFile.FindPathAndFileByClassName(stateName);

                stateWindowsNode windowNode = new stateWindowsNode(stateEditorUtils.StateList.Count);

                Vector3 transMousePos = new Vector3();
                transMousePos = stateEditorUtils.TranslationMtx.UnTransform(MousePos);

                windowNode.Set(fileAndPath, stateName, stateName, transMousePos.x, transMousePos.y, 150, 80);
                StateList.Add(windowNode);

                SaveStateWindowsNodeData(fileAndPath, stateName, (int)MousePos.x, (int)MousePos.y, 150, 80);

                fileAndPath = utlDataAndFile.FindPathAndFileByClassName(StateMachineName);

                SaveStateInfo(StateMachineName, GameObject.name);

                AddStateCodeToStateMachineCode(fileAndPath, stateName);
            }
        }
        static stateWindowsNode FindStateWindowsNodeByName(string name)
        {
            stateWindowsNode node = null;

            for (int i = 0; i < m_StateList.Count; i++)
            {
                if (m_StateList[i].ClassName == name)
                {
                    return(m_StateList[i]);
                }
            }
            return(node);
        }
        public static stateWindowsNode CreateStateWindowsNode(string typeName)
        {
            stateWindowsNode winNode = new stateWindowsNode(StateList.Count);

            winNode.ClassName = typeName;

            float  x       = 0;
            float  y       = 0;
            float  width   = 0;
            float  height  = 0;
            string winName = typeName;

//            TextAsset text = Resources.Load(typeName+".cs") as TextAsset;
            string strBuff  = "";
            string fileName = "";

            fileName = utlDataAndFile.FindPathAndFileByClassName(typeName, false);
            strBuff  = utlDataAndFile.LoadTextFromFile(fileName);
            string[] words = strBuff.Split(new char[] { '<', '>' });

            for (int i = 0; i < words.Length; i++)
            {
                if (words[i] == "alias")
                {
                    winName = words[i + 1];
                }
                if (words[i] == "posX")
                {
                    x = Convert.ToSingle(words[i + 1]);
                }
                if (words[i] == "posY")
                {
                    y = Convert.ToSingle(words[i + 1]);
                }
                if (words[i] == "sizeX")
                {
                    width = Convert.ToSingle(words[i + 1]);
                }
                if (words[i] == "sizeY")
                {
                    height = Convert.ToSingle(words[i + 1]);
                }
            }

            winNode.Set(fileName, typeName, winName, x, y, width, height);
            return(winNode);
        }
        //public const string k_StateConditionalFileAndPath = "Assets/Scripts/Common/statemachine/state_examples/stateConditionalTemplate.cs";

        /// <summary>
        /// Create the conditional code and add it to the state that has called us.
        /// </summary>
        /// <param name="fromState"></param>
        /// <param name="toState"></param>
        public static void CreateConditionalAndAddToState(string fromState, string toState)
        {
            string replaceName = fromState + "_To_" + toState;

            string text = utlDataAndFile.LoadTextFromFile(AddConditionPath);

            string modText = text.Replace(AddConditionReplace, replaceName);

            string pathAndFileName = k_PathName
                                     + "aMech"
                                     + stateEditorUtils.GameObject.name
                                     + "/"
                                     + replaceName
                                     + ".cs";


            StreamWriter writeStream = new StreamWriter(pathAndFileName);

            writeStream.Write(modText);
            writeStream.Close();

            string fileAndPathOfState = utlDataAndFile.FindPathAndFileByClassName(fromState);

            AddConditionCodeToStateCode(fileAndPathOfState, replaceName, toState);

            stateWindowsNode node = FindStateWindowsNodeByName(fromState);

            if (node != null)
            {
                /*
                 * Type windowsNodeType = Type.GetType(toState);
                 * stateConditionalBase compNode = (stateConditionalBase)Activator.CreateInstance(conditionType);*/
                for (int i = 0; i < m_StateList.Count; i++)
                {
                    if (m_StateList[i].ClassName == toState)
                    {
                        node.ConditionLineList.Add(m_StateList[i]);
                        return;
                    }
                }
            }

            //AssetDatabase.Refresh();
        }
        public static void CreateStateWindows(string fileName)
        {
            string strBuff = utlDataAndFile.LoadTextFromFile(fileName);

            PopulateStateStrings(strBuff);

            for (int i = 0; i < m_StateNameList.Count; i++)
            {
                stateWindowsNode node = CreateStateWindowsNode(m_StateNameList[i]);
                m_StateList.Add(node);
            }

            for (int i = 0; i < m_StateList.Count; i++)
            {
                string stateFileName = utlDataAndFile.FindPathAndFileByClassName(m_StateList[i].ClassName, false);
                string buffer        = utlDataAndFile.LoadTextFromFile(stateFileName);
                PopulateLinkedConditionStates(m_StateList[i], buffer);
            }
        }
        /// <summary>
        /// Parse the conditions from the state c sharp file.
        /// </summary>
        /// <param name="node"></param>
        /// <param name="strBuff"></param>
        static void PopulateLinkedConditionStates(stateWindowsNode node, string strBuff)
        {
            string[] words = strBuff.Split(new char[] { ' ', '/', '\n', '_', '(' });
            bool     lookForConditionals = false;

            for (int i = 0; i < words.Length; i++)
            {
                if (words[i] == "<ArtiMechConditions>")
                {
                    lookForConditionals = true;
                }

                if (lookForConditionals && words[i] == "new")
                {
                    //check to see if stateConditionalBase
                    Type type = Type.GetType("artiMech." + words[i + 3]);
                    if (type != null)
                    {
                        string baseOneStr   = "";
                        string baseTwoStr   = "";
                        string baseThreeStr = "";

                        baseOneStr   = type.BaseType.Name;
                        baseTwoStr   = type.BaseType.BaseType.Name;
                        baseThreeStr = type.BaseType.BaseType.BaseType.Name;

                        //if (baseOneStr == "baseState" )//|| buffer == "stateGameBase")
                        if (baseOneStr == "baseState" || baseTwoStr == "baseState" || baseThreeStr == "baseState")
                        {
                            stateWindowsNode compNode = FindStateWindowsNodeByName(words[i + 3]);
                            if (compNode != null)
                            {
                                node.ConditionLineList.Add(compNode);
                            }
                        }
                    }
                }
            }
        }
        public static void DeleteAndRemoveState(stateWindowsNode node, string className)
        {
            SaveAllVisualStateMetaData();

            string pathAndFileForClassName = utlDataAndFile.FindPathAndFileByClassName(className);
            string strBuff = utlDataAndFile.LoadTextFromFile(pathAndFileForClassName);

            string[] wordsA = strBuff.Split(new char[] { ' ', '(' });

            for (int i = 0; i < wordsA.Length; i++)
            {
                if (wordsA[i] == "new")
                {
                    Type type = Type.GetType("artiMech." + wordsA[i + 1]);

                    if (type != null)
                    {
                        string buffer = "";
                        buffer = type.BaseType.Name;
                        if (buffer == "stateConditionBase")
                        {
                            string pathAndFileForConditionClass = utlDataAndFile.FindPathAndFileByClassName(wordsA[i + 1]);
                            File.Delete(pathAndFileForConditionClass);
                        }
                    }
                }
            }

            File.Delete(pathAndFileForClassName);
            m_StateList.Remove(node);
            for (int i = 0; i < m_StateNameList.Count; i++)
            {
                if (m_StateNameList[i] == className)
                {
                    m_StateNameList.RemoveAt(i);
                    break;
                }
            }



            //Delete the state inside the statemachine.
            string pathAndFileForStateMachine = utlDataAndFile.FindPathAndFileByClassName(StateMachineName, false);

            int lineIndex = 0;

            using (StreamReader reader = new StreamReader(pathAndFileForStateMachine))
            {
                string line = "";

                while ((line = reader.ReadLine()) != null)
                {
                    lineIndex += 1;
                    if (line.IndexOf(className) >= 0)
                    {
                        break;
                    }
                }
            }

            var file = new List <string>(System.IO.File.ReadAllLines(pathAndFileForStateMachine));

            file.RemoveAt(lineIndex - 1);
            File.WriteAllLines(pathAndFileForStateMachine, file.ToArray());

            //Refresh because there is a visual bug if not done after adding a state.
            AssetDatabase.Refresh();
        }