#import <Foundation/Foundation.h>
#import <React/RCTUtils.h>

#import "RCTDocumentPicker.h"

@implementation RCTDocumentPicker

RCT_EXPORT_MODULE();

RCT_EXPORT_METHOD(PickAndRead:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
{
  RCTExecuteOnMainQueue(^{
    NSOpenPanel *panel = [NSOpenPanel openPanel];
    [panel setCanChooseDirectories:NO];
    [panel setAllowsMultipleSelection:NO];
    [panel setMessage:@"Select a spreadsheet to read"];

    [panel beginWithCompletionHandler:^(NSInteger result){
      if (result == NSModalResponseOK) {
        NSURL *selected = [[panel URLs] objectAtIndex:0];
        NSFileHandle *hFile = [NSFileHandle fileHandleForReadingFromURL:selected error:nil];
        if(hFile) {
          NSData *data = [hFile readDataToEndOfFile];
          resolve([data base64EncodedStringWithOptions:0]);
        } else reject(@"read_failure", @"Could not read selected file!", nil);
      } else reject(@"select_failure", @"No file selected!", nil);
    }];
  });
}
@end