//------------------------------------------------------------------------------
// <copyright file=”*.cs” company=”EhLib Team”>
//     Copyright (c) 2017 Dmitry V. Bolshakov   
// </copyright>
//------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.ComponentModel.Design;
using System.Collections.ObjectModel;
using System.ComponentModel.Design.Serialization;

namespace EhLib.Design
{
  internal partial class DataAxisGridAddBoundBandsDialog : Form
  {

    private DataAxisGrid grid;

    public DataAxisGridAddBoundBandsDialog()
    {
      InitializeComponent();
    }

    public static void AddBoundAxisBats(DataAxisGrid grid)
    {
      DataAxisGridAddBoundBandsDialog dlg = new DataAxisGridAddBoundBandsDialog();
      dlg.InitData(grid);
      DialogResult result = dlg.ShowDialog();
      if (result == DialogResult.OK)
      {
        Collection<PropertyAxisBar> selectedCols = dlg.GetSelectedAxisBars();
        PropertyAxisBar[] selColsArray = new PropertyAxisBar[selectedCols.Count];
        selectedCols.CopyTo(selColsArray, 0);
        grid.StaticPropBars.AddRange(selColsArray);
      }
    }

    public Collection<PropertyAxisBar> GetSelectedAxisBars()
    {
      Collection<PropertyAxisBar> colList = new Collection<PropertyAxisBar>();
      for (int i = 0; i < AxisBarListBox.Items.Count; i++)
      {
        if (AxisBarListBox.GetSelected(i) == true)
        {
          
          PropertyDescriptor prop = ((ListBoxItem)AxisBarListBox.Items[i]).PropertyDesc;
          PropertyAxisBar band;

          Type colType = grid.GetAxisBarTypeForDataType(prop.PropertyType);
          if (colType == null) continue;

          if (grid.Site != null)
          {
            IDesignerHost host = (IDesignerHost)grid.Site.GetService(typeof(IDesignerHost));
            string compName = GenerateUniqueName(prop.Name);
            if (!String.IsNullOrEmpty(compName))
              band = (PropertyAxisBar)host.CreateComponent(colType, compName);
            else
              band = (PropertyAxisBar)host.CreateComponent(colType);
          }
          else
          {
            band = (PropertyAxisBar)Activator.CreateInstance(colType);
          }

          band.DataPropertyName = prop.Name;
          //band.PropDescr = prop;
          //column.DataType = prop.PropertyType;
          //if (DataTable != null)
          //  column.MaxLength = DataTable.Columns[prop.Name].MaxLength;
          //column.defaultWidth = column.CalcDefaultWidth();
          //          column.AutoGenerated = true;
          //          column.grid = this;
          //          dynamicColumnsList.Add(column);
          //          ColIndex = ColIndex + 1;
          colList.Add(band);
        }
      }
      return colList;
    }

    private string GenerateUniqueName(string propName)
    {
      INameCreationService nameService = (INameCreationService)grid.Site.GetService(typeof(INameCreationService));
      string result = textBoxColNameFormat.Text;
      result = result.Replace("{DataPropertyName}", propName);

      int num = 0;
      string numS = "";
      while (true)
      {
        if (nameService.IsValidName(result + numS))
        {
          result = result + numS;
          break;
        }
        num = num + 1;
        numS = num.ToString();
      }

      return result;
    }

    public void InitData(DataAxisGrid grid)
    {
      this.grid = grid;
      textBoxColNameFormat.Text = grid.Name + "{DataPropertyName}Column";
      UpdateListBox();
    }

    private void UpdateListBox()
    {
      CurrencyManager cm;

      if (this.grid.DataSource == null) return;
      AxisBarListBox.Items.Clear();

      try
      {
        cm = this.BindingContext[this.grid.DataSource, this.grid.DataMember] as CurrencyManager;
      }
      catch (ArgumentException ae)
      {
        MessageBox.Show(ae.Message);
        cm = null;
      }
      if (cm == null) return;

      PropertyDescriptorCollection props = cm.GetItemProperties();

      if (props != null)
      {
        for (int i = 0; i < props.Count; i++)
        {
          if (typeof(IList).IsAssignableFrom(props[i].PropertyType))
          {
            // we have an IList. It could be a byte[] in which case we want to generate an Image column
            // 
            TypeConverter imageTypeConverter = TypeDescriptor.GetConverter(typeof(Image));
            if (!imageTypeConverter.CanConvertFrom(props[i].PropertyType))
            {
              continue;
            }
          }

          if (radioButtonNewColumns.Checked &&
              grid.StaticPropBars.FindBarByDataProperty(props[i].Name) != null)
          {
            EhLibUtils.DoNothing();
          }
          else
          {
            this.AxisBarListBox.Items.Add(new ListBoxItem(props[i], props[i].Name));
          }
        }
      }

      for (int i = 0; i < AxisBarListBox.Items.Count; i++)
      {
        AxisBarListBox.SetSelected(i, true);
      }
    }

    private void radioButtonAllColumns_Click(object sender, EventArgs e)
    {
      UpdateListBox();
    }

    private void radioButtonNewColumns_Click(object sender, EventArgs e)
    {
      UpdateListBox();
    }

    private class ListBoxItem
    {
      readonly PropertyDescriptor propertyDesc;
      readonly string propertyName;

      public ListBoxItem(PropertyDescriptor propertyDesc, string propertyName)
      {
        this.propertyDesc = propertyDesc;
        this.propertyName = propertyName;
      }

      public PropertyDescriptor PropertyDesc
      {
        get
        {
          return this.propertyDesc;
        }
      }

      //public string PropertyName
      //{
      //  get
      //  {
      //    return this.propertyName;
      //  }
      //}

      public override string ToString()
      {
        return this.propertyName + " (" + PropertyDesc.PropertyType.ToString() + ")";
      }
    }

  }
}
