using System.ComponentModel.Composition;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using DynamicXAPLoading.ViewModels;

namespace DynamicXAPLoading
{
    public partial class MainPage
    {
        public MainPage()
        {
            InitializeComponent();
            Loaded += OnLoaded;
        }

        private void OnLoaded(object sender, RoutedEventArgs e)
        {
            CompositionInitializer.SatisfyImports(this);
            DataContext = ViewModel;

            ContentFrame.Navigated += OnNavigated;
            ContentFrame.NavigationFailed += OnNavigationFailed;
        }

        // After the Frame navigates, ensure the HyperlinkButton representing the current page is selected
        private void OnNavigated(object sender, NavigationEventArgs e)
        {
            foreach (var child in LinksStackPanel.Children)
            {
                var hb = child as HyperlinkButton;
                if (hb != null && hb.NavigateUri != null)
                {
                    VisualStateManager.GoToState(hb,
                                                 hb.NavigateUri.ToString().Equals(e.Uri.ToString())
                                                     ? "ActiveLink"
                                                     : "InactiveLink", true);
                }
            }
        }

        // If an error occurs during navigation, show an error window
        private static void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
        {
            e.Handled = true;
            ChildWindow errorWin = new ErrorWindow(e.Uri);
            errorWin.Show();
        }

        [Import]
        public MainPageViewModel ViewModel { get; set; }
    }
}