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

namespace HaloObjects
{
    public class StringID : MetaNode
    {
        short Index = 0;
        byte Length = 0;
        string Name = "StringId";

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

        #region MetaNode Members

        public void Read(System.IO.BinaryReader br)
        {
            Index = br.ReadInt16();
            Length = br.ReadBytes(2)[1];
        }

        public void Read(System.IO.BinaryReader br, int Magic)
        {
            Index = br.ReadInt16();
            Length = br.ReadBytes(2)[1];
        }

        public void Write(System.IO.BinaryWriter bw)
        {
            bw.Write(Index);
            bw.Write(new byte[] { (byte)0, (byte)Length });
        }

        public object GetValue()
        {
            if (Globals.Plugin == null || ((Meta)Globals.Plugin).TagStringIds.Count == 0)
                return "";
            else
            {
                return ((Meta)Globals.Plugin).TagStringIds[Index];
            }
        }

        public void SetValue(object Value)
        {
            if ((string)Value == "Fuck")
            {
                Index = 0;
                Length = 0;
            }
            else
            {
                Index = (short)((Meta)Globals.Plugin).TagStringIds.IndexOf((string)Value);
                if (Index == -1)
                {
                    ((Meta)Globals.Plugin).TagStringIds.Add((string)Value);
                    Index = (short)((Meta)Globals.Plugin).TagStringIds.IndexOf((string)Value);
                    Length = (byte)((Meta)Globals.Plugin).TagStringIds[Index].Length;
                }
            }
        }

        public int GetSize()
        {
            return 4;
        }

        public void Compile(System.IO.BinaryWriter bw, int Magic)
        {
            short NewIndex = (short)Globals.Strings.IndexOf(((Meta)Globals.Plugin).TagStringIds[Index]);
            bw.Write(NewIndex);
            if (NewIndex == -1)
                bw.Write((short)0);
            else
                bw.Write(new byte[] { (byte)0, (byte)Globals.Strings[NewIndex].Length });
        }

        public void Decompile(System.IO.BinaryWriter bw, int Magic)
        {
            if (Index == -1)
                bw.Write(0);
            else
            {
                Globals.TagStringIds.Add(Globals.Strings[Index]);
                bw.Write((short)(Globals.TagStringIds.Count - 1));
                bw.Write(new byte[] { (byte)0, (byte)Length });
            }
        }

        public string GetName()
        {
            return Name;
        }

        #endregion

        #region ICloneable Members

        public object Clone()
        {
            StringID s = new StringID(this.Name);
            s.Index = Index;
            s.Length = Length;
            return s;
        }

        #endregion
    }
}
