using System;
using System.Threading.Tasks;
using Windows.Security.Cryptography;
using Windows.Storage;
using Windows.Storage.Pickers;
using Microsoft.ReactNative.Managed;

namespace SheetJSWin {
  [ReactModule]
  class DocumentPicker {
    private ReactContext context;
    [ReactInitializer]
    public void Initialize(ReactContext reactContext) { context = reactContext; }

    [ReactMethod("PickAndRead")]
    public async void PickAndRead(IReactPromise<string> result) {
      context.Handle.UIDispatcher.Post(async() => { try {
        var picker = new FileOpenPicker();
        picker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
        picker.FileTypeFilter.Add(".xlsx");
        picker.FileTypeFilter.Add(".xls");

        var file = await picker.PickSingleFileAsync();
        if(file == null) throw new Exception("File not found");

        var buf = await FileIO.ReadBufferAsync(file);
        result.Resolve(CryptographicBuffer.EncodeToBase64String(buf));
      } catch(Exception e) { result.Reject(new ReactError { Message = e.Message }); }});
    }
  }
}