using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Global;
using System.Windows.Forms;

namespace HaloObjects
{
    public class Ident : MetaNode
    {
        string Name = "Ident";
        int Id = -1;

        public Ident(string Name)
        {
            this.Name = Name;
        }

        #region MetaNode Members

        public void Read(System.IO.BinaryReader br)
        {
            Id = br.ReadInt32();
        }

        public void Read(System.IO.BinaryReader br, int Magic)
        {
            Id = br.ReadInt32();
        }

        public void Write(System.IO.BinaryWriter bw)
        {
            bw.Write(Id);
        }

        public object GetValue()
        {
            if (Id == -1)
                return "Null Reference";
            else
            {
                try { return ((Meta)Globals.Plugin).TagReferences[Id]; }
                catch
                {
                    MessageBox.Show("Tag Ident Fuck Up in this Reflexive/Tag!\nReport this to Grim!");
                    return "Null Reference";
                }
            }
        }

        public void SetValue(object Value)
        {
            if ((string)Value == "Null Reference")
                Id = -1;
            else
            {
                ((Meta)Globals.Plugin).TagReferences.Add((string)Value);
                Id = ((Meta)Globals.Plugin).TagReferences.IndexOf((string)Value);
            }
        }

        public int GetSize()
        {
            return 4;
        }

        public void Compile(System.IO.BinaryWriter bw, int Magic)
        {
            if (Id == -1)
            {
                bw.Write(-1);
                return;
            }
            int Index = Globals.Tags.IndexOf(((Meta)Globals.Plugin).TagReferences[Id]);
            if (Index == -1)
                bw.Write(-1);
            else
                bw.Write(Globals.Idents[Index]);
        }

        public void Decompile(System.IO.BinaryWriter bw, int Magic)
        {
            // Check Index
            int Index = Globals.Idents.IndexOf(Id);
            if (Index != -1)
            {
                Globals.TagReferences.Add(Globals.Tags[Index]);
                bw.Write(Globals.TagReferences.Count - 1);
            }
            else
                bw.Write(-1);
        }

        public string GetName()
        {
            return Name;
        }

        #endregion

        #region ICloneable Members

        public object Clone()
        {
            Ident i = new Ident(this.Name);
            i.Id = this.Id;
            return i;
        }

        #endregion
    }
}
