using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using log4net;

namespace VIZ.Framework.Core
{
    /// <summary>
    /// Winform辅助类
    /// </summary>
    public static class WinformHelper
    {
        /// <summary>
        /// 日志
        /// </summary>
        private static ILog log = LogManager.GetLogger(typeof(WinformHelper));

        /// <summary>
        /// 是否是处于设计模式
        /// </summary>
        /// <returns>是否是处于设计模式</returns>
        public static bool IsInDesignMode()
        {
            bool returnFlag = false;

            if (LicenseManager.UsageMode == LicenseUsageMode.Designtime)
            {
                returnFlag = true;
            }
            else if (Process.GetCurrentProcess().ProcessName == "devenv")
            {
                returnFlag = true;
            }

            return returnFlag;
        }

        /// <summary>
        /// 如果需要在UI线程执行，那么切换至UI线程同步执行
        /// </summary>
        /// <param name="control">控件</param>
        /// <param name="action">方法</param>
        public static void InvokeOnUiThreadIfRequired(System.Windows.Forms.Control control, Action action)
        {
            try
            {
                if (control.IsDisposed)
                    return;

                if (control.InvokeRequired)
                {
                    control.Invoke(action);
                }
                else
                {
                    action.Invoke();
                }
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
        }

        /// <summary>
        /// 如果需要在UI线程执行，那么切换至UI线程稍后执行
        /// </summary>
        /// <param name="control">控件</param>
        /// <param name="action">方法</param>
        public static void BeginInvkoeOnUiTrheadIfRequired(System.Windows.Forms.Control control, Action action)
        {
            try
            {
                if (control.IsDisposed)
                    return;

                if (control.InvokeRequired)
                {
                    control.BeginInvoke(action);
                }
                else
                {
                    action.Invoke();
                }
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
        }
    }
}
