#pragma once

#include <winrt/Windows.Storage.Pickers.h>
#include <winrt/Windows.Security.Cryptography.h>
#include "NativeModules.h"

using namespace winrt::Microsoft::ReactNative;
using namespace winrt::Windows::Storage;
using namespace winrt::Windows::Storage::Pickers;
using namespace winrt::Windows::Security::Cryptography;

namespace SheetJSWin {
  REACT_MODULE(DocumentPicker);
  struct DocumentPicker {
    REACT_INIT(Initialize);
    void Initialize(const ReactContext& reactContext) noexcept {
      context = reactContext;
    }

    REACT_METHOD(PickAndRead);
    void PickAndRead(ReactPromise<winrt::hstring> promise) noexcept {
      auto prom = promise;
      context.UIDispatcher().Post([prom = std::move(prom)]()->winrt::fire_and_forget {
        auto p = prom;
        FileOpenPicker picker;
        picker.SuggestedStartLocation(PickerLocationId::DocumentsLibrary);
        picker.FileTypeFilter().Append(L".xlsx");
        picker.FileTypeFilter().Append(L".xls");

        StorageFile file = co_await picker.PickSingleFileAsync();
        if(file == nullptr) { p.Reject("File not Found"); co_return; }

        auto buf = co_await FileIO::ReadBufferAsync(file);
        p.Resolve(CryptographicBuffer::EncodeToBase64String(buf));
        co_return;
      });
    }

    private:
      ReactContext context{nullptr};
  };
}