/*******************************************************
 * Copyright (C) 2018 XMind Ltd. - All Rights Reserved
 *******************************************************/

#import <Foundation/Foundation.h>
#import <StoreKit/StoreKit.h>
#import <iostream>
#import <napi.h>
#import "./iap.h"

// 辅助函数：将 N-API 字符串转换为 NSString
NSString* ToNSString(const std::string& value) {
  return [[NSString alloc] initWithUTF8String:value.c_str()];
}

// 简单函数实现

Napi::Value IapCanMakePayments(const Napi::CallbackInfo& info) {
  Napi::Env env = info.Env();

  @autoreleasepool {
    bool canMakePayments = [SKPaymentQueue canMakePayments];
    return Napi::Boolean::New(env, canMakePayments);
  }
}

Napi::Value IapGetReceiptURL(const Napi::CallbackInfo& info) {
  Napi::Env env = info.Env();

  @autoreleasepool {
    NSURL* url = [[NSBundle mainBundle] appStoreReceiptURL];

    if (url != nil) {
      return Napi::String::New(env, url.fileSystemRepresentation);
    } else {
      return Napi::String::New(env, "");
    }
  }
}

Napi::Value IapFinishAllTransactions(const Napi::CallbackInfo& info) {
  Napi::Env env = info.Env();

  @autoreleasepool {
    for (SKPaymentTransaction* transaction in SKPaymentQueue.defaultQueue.transactions) {
      [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
    }
  }

  return env.Undefined();
}

Napi::Value IapFinishTransactionByDate(const Napi::CallbackInfo& info) {
  Napi::Env env = info.Env();

  if (info.Length() < 1 || !info[0].IsString()) {
    Napi::TypeError::New(env, "Invalid arguments").ThrowAsJavaScriptException();
    return env.Undefined();
  }

  std::string dateStr = info[0].As<Napi::String>().Utf8Value();

  @autoreleasepool {
    // 创建日期格式化器
    NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
    NSLocale* enUSPOSIXLocale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
    [dateFormatter setLocale:enUSPOSIXLocale];
    [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZZZ"];

    // 删除交易记录
    NSString* transactionDate = ToNSString(dateStr);

    for (SKPaymentTransaction* transaction in SKPaymentQueue.defaultQueue.transactions) {
      if ([transactionDate isEqualToString:[dateFormatter stringFromDate:transaction.transactionDate]]) {
        [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
      }
    }
  }

  return env.Undefined();
}