#include <nan.h>
#import <Foundation/Foundation.h>
//#include <node.h>

using namespace v8;

NAN_METHOD(getDefaultApplication) {
  Nan::HandleScope();

  NSLog(@"getDefaultApplication...");

  if (info.Length() != 1)
  {
    return Nan::ThrowError("Invalid number of arguments");
  }

  NSString *filenameExtension  = @"";

  if (info[0]->IsString()) {
    String::Utf8Value str(info[0]->ToString());
    std::string foo = std::string(*str);
    filenameExtension = @(foo.c_str());
    NSLog(@"Input Extension = %@", filenameExtension);
  }


  NSString *UTI = (__bridge NSString *)UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)filenameExtension, NULL);
  if (UTI != NULL) {
    NSLog(@"Universal Type Identifier = %@", UTI);

    CFURLRef helperApplicationURL = LSCopyDefaultApplicationURLForContentType((__bridge CFStringRef)UTI, kLSRolesEditor, NULL);
    //CFURLRef helperApplicationURL = LSCopyDefaultApplicationURLForContentType((__bridge CFStringRef)UTI, kLSRolesAll, NULL);

    if (helperApplicationURL != NULL) {
        // Check to make sure the registered helper application isn't us
        NSString *helperApplicationPath = [(__bridge NSURL *)helperApplicationURL path];
        NSString *helperApplicationName = [[NSFileManager defaultManager] displayNameAtPath:helperApplicationPath];

        CFRelease(helperApplicationURL);

        Nan::MaybeLocal<String> resultString = Nan::New(helperApplicationName.UTF8String);
        info.GetReturnValue().Set(resultString.ToLocalChecked());
        NSLog(@"getDefaultApplication = %@", helperApplicationName);
    }
    else{
        //return nil;
        info.GetReturnValue().Set(Nan::New("").ToLocalChecked());
        NSLog(@"getDefaultApplication = NOT FOUND");
    }
  }
}


NAN_MODULE_INIT(init) {
  Nan::Set(target,
    Nan::New("getDefaultApplication").ToLocalChecked(),
    Nan::GetFunction(Nan::New<FunctionTemplate>(getDefaultApplication)).ToLocalChecked());

}

NODE_MODULE(osxLaunchServices, init)
