using System;
using System.Windows.Forms;

namespace rglib.libtest {
    public partial class CodogrammEditDialog : Form {
        private readonly Codogramm _codogrammData;

        public CodogrammEditDialog() : this(new Codogramm()) {

        }

        public CodogrammEditDialog(Codogramm codogrammData) {
            InitializeComponent();
            _codogrammData = codogrammData;
        }

        private void checkBox17_CheckedChanged(object sender, EventArgs e) {
        }

        public Codogramm CodogrammData => _codogrammData;

        private void OnValueChanged(object sender, EventArgs e) {
            UpdateBitsEnabled();
            ApplyBitsFrom(_codogrammData.CodogrammBody);
        }

        private void groupBox1_Enter(object sender, EventArgs e) {
        }

        private void CodogrammEditWindow_Load(object sender, EventArgs e) {
            codogrammLengthUpDown.Value = _codogrammData.LengthBits;
            codogramNumUpDown.Value = _codogrammData.Number;
            textBox1.Text = _codogrammData.Name;
            ApplyBitsFrom(_codogrammData.CodogrammBody);
        }

        void UpdateBitsEnabled() {
            int index = 0;

            for (index = Convert.ToInt32(codogrammLengthUpDown.Minimum);
                index <= Convert.ToInt32(codogrammLengthUpDown.Maximum);
                index++) {
                var target = groupBox1.Controls[$"checkBox{index}"];
                target.Enabled = index <= Convert.ToInt32(codogrammLengthUpDown.Value);
            }
        }

        void ApplyBitsFrom(uint data) {
            uint loclData = data;
            for (int index = 0; index < Convert.ToInt32(codogrammLengthUpDown.Value); index++) {
                var target = groupBox1.Controls[$"checkBox{index + 1}"];
                ((CheckBox) target).Checked = ((loclData >> index) & 1) == 1;
            }
        }

        private uint GetUintFromBits() {
            uint localValue = 0;
            for (int index = 0; index < Convert.ToInt32(codogrammLengthUpDown.Value); index++) {
                var target = groupBox1.Controls[$"checkBox{index + 1}"];
                localValue |= (uint) ((((CheckBox) target).Checked ? 1 : 0) << index);
            }

            return localValue;
        }

        private void saveButton_Click(object sender, EventArgs e) {
            _codogrammData.CodogrammBody = GetUintFromBits();
            _codogrammData.Name = textBox1.Text;
            _codogrammData.LengthBits = Convert.ToByte(codogrammLengthUpDown.Value);

            DialogResult = DialogResult.OK;
            Close();
        }

    }
}

