<commit_before>﻿using Crystal3;
using Crystal3.Core;
using Crystal3.InversionOfControl;
using Crystal3.Model;
using Crystal3.Navigation;
using Crystal3.UI.Commands;
using Crystal3.UI.MessageDialog;
using Neptunium.Data;
using Neptunium.Fragments;
using Neptunium.Logging;
using Neptunium.Managers;
using Neptunium.Media;
using Neptunium.Services.SnackBar;
using Neptunium.Shared;
using NotificationsExtensions;
using NotificationsExtensions.Tiles;
using NotificationsExtensions.Toasts;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Data.Xml.Dom;
using Windows.Foundation.Collections;
using Windows.Media.Playback;
using Windows.Storage;
using Windows.UI.Notifications;
using Windows.UI.Xaml.Navigation;

namespace Neptunium.ViewModel
{
    public class AppShellViewModel : UIViewModelBase
    {
        private NavigationService InlineNavigationService = null;
        public AppShellViewModel()
        {
            LogManager.Info(typeof(AppShellViewModel), "AppShellViewModel .ctor");

            if (!IoC.Current.IsRegistered<IMessageDialogService>())
                IoC.Current.Register<IMessageDialogService>(new DefaultMessageDialogService());

            GoToStationsViewCommand = new RelayCommand(x =>
            {
                if (!InlineNavigationService.IsNavigatedTo<StationsViewViewModel>())
                    InlineNavigationService.NavigateTo<StationsViewViewModel>();
            });

            GoToNowPlayingViewCommand = new RelayCommand(x =>
            {
                if (!InlineNavigationService.IsNavigatedTo<NowPlayingViewViewModel>())
                    InlineNavigationService.NavigateTo<NowPlayingViewViewModel>();
            });

            GoToSettingsViewCommand = new RelayCommand(x =>
            {
                if (!InlineNavigationService.IsNavigatedTo<SettingsViewViewModel>())
                    InlineNavigationService.NavigateTo<SettingsViewViewModel>();
            });

            GoToSongHistoryViewCommand = new RelayCommand(x =>
            {
                if (!InlineNavigationService.IsNavigatedTo<SongHistoryViewModel>())
                    InlineNavigationService.NavigateTo<SongHistoryViewModel>();
            });

            PlayCommand = new RelayCommand(x =>
            {
                BackgroundMediaPlayer.Current.Play();
            }, x =>
            {
                var currentPlayerState = BackgroundMediaPlayer.Current.PlaybackSession.PlaybackState;

                return currentPlayerState != MediaPlaybackState.Buffering &&
                currentPlayerState != MediaPlaybackState.Opening &&
                currentPlayerState != MediaPlaybackState.Playing;
            });

            PauseCommand = new RelayCommand(x =>
            {
                if (BackgroundMediaPlayer.Current.PlaybackSession.CanPause)
                    BackgroundMediaPlayer.Current.Pause();
            }, x => { try { return BackgroundMediaPlayer.Current.PlaybackSession.CanPause; } catch (Exception) { return true; } });


            HandoffStationCommand = new ManualRelayCommand(x =>
            {

            });

            HandOffViewFragment = new HandOffFlyoutViewFragment();
            NowPlayingView = new NowPlayingViewFragment();
            SleepTimerViewFragment = new SleepTimerFlyoutViewFragment();

            WindowManager.GetStatusManagerForCurrentWindow().NormalStatusText = "Neptunium"; //"Hanasu Alpha";

            UpdateLiveTile();
        }

        private async void CarModeManager_CarModeManagerCarModeStatusChanged(object sender, CarModeManagerCarModeStatusChangedEventArgs e)
        {
            await UpdateCarModeButtonStatusAsync(e.IsInCarMode);
        }

        private async Task UpdateCarModeButtonStatusAsync(bool IsInCarMode)
        {
            await App.Dispatcher.RunWhenIdleAsync(() =>
            {
                if (ShowCarModeStatusButton != IsInCarMode)
                {
                    IoC.Current.Resolve<ISnackBarService>().ShowSnackAsync((IsInCarMode ? "Car Mode Activated" : "Car Mode Deactivated"), 3000);

                    ShowCarModeStatusButton = IsInCarMode;
                }
            });
        }

        protected override async void OnNavigatedTo(object sender, CrystalNavigationEventArgs e)
        {
            LogManager.Info(typeof(AppShellViewModel), "AppShellViewModel OnNavigatedTo");

            InlineNavigationService = Crystal3.Navigation.WindowManager.GetNavigationManagerForCurrentWindow()
                .GetNavigationServiceFromFrameLevel(Crystal3.Navigation.FrameLevel.Two);

            if (!StationMediaPlayer.IsInitialized)
                await StationMediaPlayer.InitializeAsync();

            StationMediaPlayer.MetadataChanged += ShoutcastStationMediaPlayer_MetadataChanged;
            StationMediaPlayer.CurrentStationChanged += ShoutcastStationMediaPlayer_CurrentStationChanged;
            StationMediaPlayer.BackgroundAudioError += ShoutcastStationMediaPlayer_BackgroundAudioError;

            CarModeManager.CarModeManagerCarModeStatusChanged += CarModeManager_CarModeManagerCarModeStatusChanged;

            StationMediaPlayer.ConnectingStatusChanged += StationMediaPlayer_ConnectingStatusChanged;

            BackgroundMediaPlayer.Current.CurrentStateChanged += Current_CurrentStateChanged;

            ContinuedAppExperienceManager.CheckForReverseHandoffOpportunities();

            await UpdateCarModeButtonStatusAsync(CarModeManager.IsInCarMode);
        }

        private void Current_CurrentStateChanged(MediaPlayer sender, object args)
        {
            HandoffStationCommand.SetCanExecute(sender.PlaybackSession.PlaybackState == MediaPlaybackState.Playing);
        }

        protected override void OnNavigatedFrom(object sender, CrystalNavigationEventArgs e)
        {
            StationMediaPlayer.ConnectingStatusChanged -= StationMediaPlayer_ConnectingStatusChanged;

            base.OnNavigatedFrom(sender, e);
        }


        private void StationMediaPlayer_ConnectingStatusChanged(object sender, StationMediaPlayerConnectingStatusChangedEventArgs e)
        {
            App.Dispatcher.RunWhenIdleAsync(() => IsBusy = e.IsConnecting);
        }<commit_msg>Initialize Car Mode manager on AppShellViewModel-OnNavigatedTo if it isn't already initialized for some reason.<commit_after>﻿using Crystal3;
using Crystal3.Core;
using Crystal3.InversionOfControl;
using Crystal3.Model;
using Crystal3.Navigation;
using Crystal3.UI.Commands;
using Crystal3.UI.MessageDialog;
using Neptunium.Data;
using Neptunium.Fragments;
using Neptunium.Logging;
using Neptunium.Managers;
using Neptunium.Media;
using Neptunium.Services.SnackBar;
using Neptunium.Shared;
using NotificationsExtensions;
using NotificationsExtensions.Tiles;
using NotificationsExtensions.Toasts;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Data.Xml.Dom;
using Windows.Foundation.Collections;
using Windows.Media.Playback;
using Windows.Storage;
using Windows.UI.Notifications;
using Windows.UI.Xaml.Navigation;

namespace Neptunium.ViewModel
{
    public class AppShellViewModel : UIViewModelBase
    {
        private NavigationService InlineNavigationService = null;
        public AppShellViewModel()
        {
            LogManager.Info(typeof(AppShellViewModel), "AppShellViewModel .ctor");

            if (!IoC.Current.IsRegistered<IMessageDialogService>())
                IoC.Current.Register<IMessageDialogService>(new DefaultMessageDialogService());

            GoToStationsViewCommand = new RelayCommand(x =>
            {
                if (!InlineNavigationService.IsNavigatedTo<StationsViewViewModel>())
                    InlineNavigationService.NavigateTo<StationsViewViewModel>();
            });

            GoToNowPlayingViewCommand = new RelayCommand(x =>
            {
                if (!InlineNavigationService.IsNavigatedTo<NowPlayingViewViewModel>())
                    InlineNavigationService.NavigateTo<NowPlayingViewViewModel>();
            });

            GoToSettingsViewCommand = new RelayCommand(x =>
            {
                if (!InlineNavigationService.IsNavigatedTo<SettingsViewViewModel>())
                    InlineNavigationService.NavigateTo<SettingsViewViewModel>();
            });

            GoToSongHistoryViewCommand = new RelayCommand(x =>
            {
                if (!InlineNavigationService.IsNavigatedTo<SongHistoryViewModel>())
                    InlineNavigationService.NavigateTo<SongHistoryViewModel>();
            });

            PlayCommand = new RelayCommand(x =>
            {
                BackgroundMediaPlayer.Current.Play();
            }, x =>
            {
                var currentPlayerState = BackgroundMediaPlayer.Current.PlaybackSession.PlaybackState;

                return currentPlayerState != MediaPlaybackState.Buffering &&
                currentPlayerState != MediaPlaybackState.Opening &&
                currentPlayerState != MediaPlaybackState.Playing;
            });

            PauseCommand = new RelayCommand(x =>
            {
                if (BackgroundMediaPlayer.Current.PlaybackSession.CanPause)
                    BackgroundMediaPlayer.Current.Pause();
            }, x => { try { return BackgroundMediaPlayer.Current.PlaybackSession.CanPause; } catch (Exception) { return true; } });


            HandoffStationCommand = new ManualRelayCommand(x =>
            {

            });

            HandOffViewFragment = new HandOffFlyoutViewFragment();
            NowPlayingView = new NowPlayingViewFragment();
            SleepTimerViewFragment = new SleepTimerFlyoutViewFragment();

            WindowManager.GetStatusManagerForCurrentWindow().NormalStatusText = "Neptunium"; //"Hanasu Alpha";

            UpdateLiveTile();
        }

        private async void CarModeManager_CarModeManagerCarModeStatusChanged(object sender, CarModeManagerCarModeStatusChangedEventArgs e)
        {
            await UpdateCarModeButtonStatusAsync(e.IsInCarMode);
        }

        private async Task UpdateCarModeButtonStatusAsync(bool IsInCarMode)
        {
            await App.Dispatcher.RunWhenIdleAsync(() =>
            {
                if (ShowCarModeStatusButton != IsInCarMode)
                {
                    IoC.Current.Resolve<ISnackBarService>().ShowSnackAsync((IsInCarMode ? "Car Mode Activated" : "Car Mode Deactivated"), 3000);

                    ShowCarModeStatusButton = IsInCarMode;
                }
            });
        }

        protected override async void OnNavigatedTo(object sender, CrystalNavigationEventArgs e)
        {
            LogManager.Info(typeof(AppShellViewModel), "AppShellViewModel OnNavigatedTo");

            InlineNavigationService = Crystal3.Navigation.WindowManager.GetNavigationManagerForCurrentWindow()
                .GetNavigationServiceFromFrameLevel(Crystal3.Navigation.FrameLevel.Two);

            if (!StationMediaPlayer.IsInitialized)
                await StationMediaPlayer.InitializeAsync();

            StationMediaPlayer.MetadataChanged += ShoutcastStationMediaPlayer_MetadataChanged;
            StationMediaPlayer.CurrentStationChanged += ShoutcastStationMediaPlayer_CurrentStationChanged;
            StationMediaPlayer.BackgroundAudioError += ShoutcastStationMediaPlayer_BackgroundAudioError;

            CarModeManager.CarModeManagerCarModeStatusChanged += CarModeManager_CarModeManagerCarModeStatusChanged;

            if (!CarModeManager.IsInitialized)
                await CarModeManager.InitializeAsync();

            StationMediaPlayer.ConnectingStatusChanged += StationMediaPlayer_ConnectingStatusChanged;

            BackgroundMediaPlayer.Current.CurrentStateChanged += Current_CurrentStateChanged;

            ContinuedAppExperienceManager.CheckForReverseHandoffOpportunities();

            await UpdateCarModeButtonStatusAsync(CarModeManager.IsInCarMode);
        }

        private void Current_CurrentStateChanged(MediaPlayer sender, object args)
        {
            HandoffStationCommand.SetCanExecute(sender.PlaybackSession.PlaybackState == MediaPlaybackState.Playing);
        }

        protected override void OnNavigatedFrom(object sender, CrystalNavigationEventArgs e)
        {
            StationMediaPlayer.ConnectingStatusChanged -= StationMediaPlayer_ConnectingStatusChanged;

            base.OnNavigatedFrom(sender, e);
        }


        private void StationMediaPlayer_ConnectingStatusChanged(object sender, StationMediaPlayerConnectingStatusChangedEventArgs e)
        {
            App.Dispatcher.RunWhenIdleAsync(() => IsBusy = e.IsConnecting);
        }
{'fraction_non_alphanumeric': 0.07380392156862745, 'fraction_numerical': 0.00203921568627451, 'mean_word_length': 2.858093797276853, 'pattern_counts': {'":': 0, '<': 25, '<?xml version=': 0, '>': 47, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '360634', 'n_tokens_mistral': 3190, 'n_tokens_neox': 2993, 'n_words': 487}