using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Media;
using System.Windows;

namespace SlnMesnac.WPF.MessageTips
{
    public static class Msg
    {
        private static MessageAdorner messageAdorner;
        /// <summary>
        /// 消息弹出
        /// </summary>
        /// <param name="message">消息内容</param>
        /// <param name="msgtype">消息类型;0正常，1警告，2错误</param>
        /// <param name="outTime">自动关闭时间。默认5秒</param>
        /// <exception cref="Exception"></exception>
        public static void MsgShow(string message, int msgtype, int outTime = 3)
        {
            try
            {
                Application.Current.Dispatcher.Invoke(() =>
                {
                    if (messageAdorner != null && messageAdorner.IsLoaded)
                    {
                        messageAdorner.PushMessage(message, msgtype, outTime);
                        return;
                    }
                    Window win = null;
                    if (Application.Current.Windows.Count > 0)
                    {
                        win = Application.Current.Windows.OfType<Window>().FirstOrDefault(o => o.IsActive);
                        if (win == null)
                            win = Application.Current.Windows.OfType<Window>().First(o => o.IsActive);
                    }

                    var layer = GetAdornerLayer(win);
                    if (layer == null)
                        throw new Exception("not AdornerLayer is null");
                    messageAdorner = new MessageAdorner(layer);
                    layer.Add(messageAdorner);
                    messageAdorner.PushMessage(message, msgtype, outTime);

                });
               
            }catch(Exception ex)
            {
                Console.WriteLine("MsgShow异常:"+ex.Message);
            }
        }
        static AdornerLayer GetAdornerLayer(Visual visual)
        {
            var decorator = visual as AdornerDecorator;
            if (decorator != null)
                return decorator.AdornerLayer;
            var presenter = visual as ScrollContentPresenter;
            if (presenter != null)
                return presenter.AdornerLayer;
            var visualContent = (visual as Window)?.Content as Visual;
            return AdornerLayer.GetAdornerLayer(visualContent ?? visual);
        }
    }
}
