using NEIntelligentControl2.Models.Pages;
using NEIntelligentControl2.Models.User;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace NEIntelligentControl2.Windows
{
    /// <summary>
    /// 用户登录窗口
    /// </summary>
    public partial class UserWindow : Window
    {
        private IPageAction _IPageAction;
        public UserWindow(IPageAction ipa)
        {
            InitializeComponent();
            _IPageAction = ipa;
        }

        internal bool Show(string tag)
        {
            SwitchPage(tag);

            this.Owner = Application.Current.MainWindow;
            var v = this.ShowDialog();
            return v != null && v == true;
        }

        internal bool Show(string tag, UserInfo user)
        {
            var page = _IPageAction[tag] as Pages.User.PageUserEdit;

            page.EditUser(user);

            SwitchPage(page);

            this.Owner = Application.Current.MainWindow;
            var v = this.ShowDialog();
            return v != null && v == true;
        }

        private void SwitchPage(string tag)
        {
            Page page = _IPageAction[tag];
            SwitchPage(page);
        }

        private void SwitchPage(Page page)
        {
            if (page is IPageMessage pg)
            {
                pg.OnMessage = OnPageMessage;
            }

            _Frame.Navigate(page);

            if (!_Frame.NavigationService.CanGoBack) return;
            var en = _Frame.NavigationService.RemoveBackEntry();
            while (en != null)
            {
                en = _Frame.NavigationService.RemoveBackEntry();
            }
        }

        private void OnPageMessage(object obj)
        {
            if(obj.ToString() == "success")
            {
                this.DialogResult = true;
                return;
            }
            SwitchPage(obj as string);
        }

        private void ContentControl_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            this.DialogResult = false;
        }
    }
}
