using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Windows.Storage;
using Windows.Storage.Pickers;

namespace Harmonia.WinUI.Storage;

public class WindowsStorageProvider : IStorageProvider
{
    private static MainWindow MainWindow => App.ServiceProvider.GetRequiredService<MainWindow>();

    public async Task<string?> GetSingleFileAsync(FilePickerOptions? options = null)
    {
        FileOpenPicker fileOpenPicker = GetFileOpenPicker(options);
        InitializePicker(fileOpenPicker);

        StorageFile? storageFile = await fileOpenPicker.PickSingleFileAsync();

        return storageFile?.Path;
    }

    public async Task<string[]> GetFilesAsync(FilePickerOptions? options = null)
    {
        FileOpenPicker fileOpenPicker = GetFileOpenPicker(options);
        InitializePicker(fileOpenPicker);

        var storageFiles = await fileOpenPicker.PickMultipleFilesAsync();

        return [.. storageFiles.Select(storageFile => storageFile.Path)];
    }

    private static FileOpenPicker GetFileOpenPicker(FilePickerOptions? options = null)
    {
        FilePickerOptions filePickerOptions = options ?? new();

        FileOpenPicker fileOpenPicker = new()
        {
            ViewMode = GetViewMode(filePickerOptions.ViewMode)
        };

        string[] filters = GetFilters(filePickerOptions.FileTypeFilter);

        foreach (string filter in filters)
        {
            fileOpenPicker.FileTypeFilter.Add(filter);
        }

        if (filePickerOptions.FileTypeFilter.Count == 0)
        {
            fileOpenPicker.FileTypeFilter.Add("*");
        }

        return fileOpenPicker;
    }

    private static PickerViewMode GetViewMode(StoragePickerViewMode viewMode)
    {
        return viewMode switch
        {
            StoragePickerViewMode.Thumbnail => PickerViewMode.Thumbnail,
            _ => PickerViewMode.List,
        };
    }

    private static string[] GetFilters(IReadOnlyList<FilePickerFileType> fileTypes)
    {
        return [.. fileTypes.SelectMany(fileType => fileType.Patterns)];
    }

    public async Task<string?> GetPathAsync()
    {
        var folderPicker = new FolderPicker
        {
            ViewMode = PickerViewMode.Thumbnail
        };
        folderPicker.FileTypeFilter.Add("*");

        InitializePicker(folderPicker);

        StorageFolder? folder = await folderPicker.PickSingleFolderAsync();

        return folder?.Path;
    }

    private static void InitializePicker(object target)
    {
        var hWnd = WinRT.Interop.WindowNative.GetWindowHandle(MainWindow);
        WinRT.Interop.InitializeWithWindow.Initialize(target, hWnd);
    }
}