using ButcherFactory.BO;
using ButcherFactory.BO.LocalBL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Speech.Synthesis;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ButcherFactory.Utils
{
  public static class ControlsUtil
  {
    public static void EBindComboBox<T>(this ComboBox box, Func<T, bool> SetSelectIndex = null, int top = 10, params string[] extendFields)
      where T : BaseInfo, new()
    {
      box.DisplayMember = "Name";
      box.ValueMember = "ID";

      var list = BaseInfoBL.GetList<T>(top, extendFields: extendFields);
      box.DataSource = list;
      if (SetSelectIndex != null)
      {
        var idx = list.FindIndex(x => SetSelectIndex(x));
        if (idx > 0)
          box.SelectedIndex = idx;
      }
      box.Refresh();
    }

    public static void EBindComboBox<T>(this ComboBox box, List<T> source)
      where T : BaseInfo, new()
    {
      box.DisplayMember = "Name";
      box.ValueMember = "ID";
      box.DataSource = source;
      box.Refresh();
    }

    public static Form GetParentFormm(Control control)
    {
      if (control.Parent != null)
      {
        if (control.Parent is Form)
        {
          return control.Parent as Form; ;
        }
        else
        {
          return GetParentFormm(control.Parent);
        }
      }
      return control as Form;
    }

    public static string ParseCode(string url)
    {
      if (url.Contains("?"))
      {
        var arr = url.Split(new char[] { '?' });
        if (arr.Length > 1)
        {
          var list = arr[1].Split(new char[] { '&' }, StringSplitOptions.RemoveEmptyEntries);
          foreach (var item in list)
          {
            var l = item.Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries);
            if (l.Length == 2 && l[0].ToUpper() == "CODE")
              return l[1].Trim();
          }
          return string.Empty;
        }
        return string.Empty;
      }
      return url.Trim();
    }

    private static readonly SpeechSynthesizer _speechSynthesizer = new SpeechSynthesizer() { Rate = 1, Volume = 100 };

    public static void PlanVoice(string text)
    {
      if (!string.IsNullOrEmpty(text))
        _speechSynthesizer.SpeakAsync(text);
    }
  }
}
