using System;
using Avalonia.Controls;
using Avalonia.Interactivity;
using Avalonia.Platform.Storage;
using LauncherGUI.ViewModels;
using Plombir;

namespace LauncherGUI.Views;

public partial class SettingsWindow : Window
{
    private MainWindowViewModel _mainWindowVM;
    public SettingsWindow(MainWindowViewModel mainWindowVM)
    {
        InitializeComponent();
        _mainWindowVM = mainWindowVM;
    }

    private async void OnFilePickerClick(object sender, RoutedEventArgs args)
    {
        // Get top level from the current control. Alternatively, you can use Window reference instead.
        var topLevel = TopLevel.GetTopLevel(this);

        if (topLevel is null) throw new NullReferenceException("Failed to start file picker!");
        // Start async operation to open the dialog.
        var files = await topLevel.StorageProvider.OpenFolderPickerAsync(new FolderPickerOpenOptions
        {
            Title = "Select directory for minecraft",
            AllowMultiple = false
        });

        if (files.Count >= 1)
        {
            var location = files[0].TryGetLocalPath();
            if (location is null) throw new NullReferenceException("Invalid location selected!");
            _mainWindowVM.RuntimeLocation = location;
            System.Console.WriteLine($"Selected {_mainWindowVM.RuntimeLocation}.");
            ConfigManager.WriteInConfig("runtime-path", location);
        }
    }
}