using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Reflection;

namespace HaloControls
{
    public partial class Bitmask : UserControl
    {
        public int Index;
        int BitCount = 0;

        public Bitmask(string Description, string[] Options, object Value, int BitCount, int Index)
        {
            InitializeComponent();

            //Suspend Layout
            this.SuspendLayout();

            this.Index = Index;
            label1.Text = Description;
            this.BitCount = BitCount;

            //Get Bits
            bool[] Bits = new bool[BitCount];
            uint num = 1;
            for (int i = 0; i < BitCount; i++)
            {
                Bits[i] = (num & (int)Value) == num;
                num = num << 1;
            }
                

            for (int i = 0; i < Options.Length; i++)
            {
                if (Options[i] != "")
                {
                    checkedListBox1.Items.Add(Options[i].Replace("_", " "));
                    checkedListBox1.SetItemChecked(checkedListBox1.Items.Count - 1, Bits[i]);
                }
            }
            checkedListBox1.Size = new Size(275, (Options.Length * 18));

            //Resume
            this.ResumeLayout();
        }

        public void Reload(object Value)
        {
            bool[] Bits = new bool[BitCount];
            uint num = 1;
            for (int i = 0; i < checkedListBox1.Items.Count; i++)
            {
                // Get Bit
                Bits[i] = (num & (int)Value) == num;
                num = num << 1;

                // Set Bit
                try { checkedListBox1.SetItemChecked(i, Bits[i]); }
                catch { }
            }
        }

        public object Save()
        {
            int num = 1;
            int num2 = 0;
            for (int i = 0; i < checkedListBox1.Items.Count; i++)
            {
                if (checkedListBox1.GetItemChecked(i))
                {
                    num2 += num;
                }
                num = num << 1;
            }

            // Saves some bitching later
            if (BitCount == 8)
                return (byte)num2;
            else if (BitCount == 16)
                return (short)num2;
            else
                return num2;
        }
    }
}
