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

namespace VIZ.Framework.Core
{
    /// <summary>
    /// 视图模型基类
    /// </summary>
    public abstract class ViewModelBase : ModelBase
    {
        /// <summary>
        /// 视图
        /// </summary>
        public WeakReference<FrameworkElement> View { get; protected set; }

        /// <summary>
        /// 是否已经完成加载
        /// </summary>
        protected bool IsAlreadyLoaded;

        /// <summary>
        /// 获取视图
        /// </summary>
        /// <typeparam name="T">视图类型</typeparam>
        /// <returns>视图</returns>
        public T GetView<T>() where T : FrameworkElement
        {
            if (this.View == null)
                return null;

            if (!this.View.TryGetTarget(out FrameworkElement view))
                return null;

            return view as T;
        }

        /// <summary>
        /// 获取窗口
        /// </summary>
        /// <returns>窗口</returns>
        public Window GetWindow()
        {
            FrameworkElement view = this.GetView<FrameworkElement>();
            if (view == null)
                return null;

            Window window = WPFHelper.GetAncestorByType<Window>(view);
            return window;
        }

        /// <summary>
        /// 设置视图
        /// </summary>
        /// <param name="view">视图</param>
        public void SetView(FrameworkElement view)
        {
            this.View = new WeakReference<FrameworkElement>(view);
        }
    }
}
