//
//  KMPurchaseManager.swift
//  PDF Master
//
//  Created by lizhe on 2023/6/1.
//

import Cocoa
        
@objc enum KMPurchaseManagerState: Int, CaseIterable {
    case unknow = 0//"unknow"
    case trial = 1//"Trial" //试用
    case trialExpired = 2//"Trial Expired" //试用过期
    case subscription = 3//"Subscription" //订阅
    case subscriptionExpired = 4//"Subscription Expired" //订阅过期
}

#if VERSION_DMG

#endif

typealias KMPurchaseCompletion = (_ isSuccess: Bool, _ error: KMInAppPurchaseState) -> Void
typealias KMPurchaseFetchProductCompletion = (_ isSuccess: Bool, _ products: Array<Any>, _ error: KMInAppPurchaseState?) -> Void
typealias KMPurchaseRestoreCompletion = (_ isSuccess: Bool, _ error: KMInAppPurchaseState) -> Void
typealias KMPurchaseCheckSubscriptionStatusCompletion = (_ isSubscription: Bool) -> Void
class KMPurchaseManager: NSObject {
    public static let manager = KMPurchaseManager()
    
    var state: KMPurchaseManagerState {
        get {
#if DEBUG
            //方便调整订阅状态
//            return .subscriptionExpired
#endif
            let info = KMLightMemberManager.manager.info.subscriptionInfoList
            var tempState: KMPurchaseManagerState = .unknow
            if info.count > 0 {
                let isSubscription = false
                for item in info {
                    switch item.status {
                    case 0:
                        tempState = .unknow
                    case 1:
                        tempState = .subscription
                    case 2:
                        tempState = .subscriptionExpired
                    case 3:
                        tempState = .trial
                    case 4:
                        tempState = .trialExpired
                    default:
                        tempState = .unknow
                    }
                }
            }
            return tempState
        }
    }
    var availableProducts: [KMProduct] = []
    
    override init() {
        super.init()
    }
    
    func fetchProducts(completeion: @escaping KMPurchaseFetchProductCompletion) {
        KMPrint("获取产品中")
#if VERSION_FREE
        KMPrint("正在获取产品中AppStore")
        KMInAppPurchaseManager.manager.fetchProducts(completion: completeion)
#endif
        
#if VERSION_DMG
        KMPrint("正在获取产品中DMG")
        KMDMGPurchaseManager.manager.fetchProducts(completion: completeion)
#endif
    }
    
    func purchaseProduct(productIdentifier: String, completion: @escaping KMPurchaseCompletion) {
        KMPrint("准备订阅中")
#if VERSION_FREE
        KMPrint("正在订阅中AppStore")
        
        let userId: String = KMLightMemberManager.manager.info.id
        KMRequestServerManager.manager.createOrder(productId: "21", userId: userId) { success, orderId, result in
            if success {
                if orderId?.count != 0 {
                    KMInAppPurchaseManager.manager.purchaseProduct(productIdentifier: PRODUCT_1, orderId: orderId!) { isSuccess, error in
                        if isSuccess {
                            completion(true, error)
                        } else {
                            completion(false, error)
                        }
                    }
                }
            } else {
                completion(false, .orderFailed)
            }
        }
#endif
        
#if VERSION_DMG
        KMPrint("正在订阅中DMG")
        var email: String = UserDefaults.standard.value(forKey: "kLoginEmail") as? String ?? ""
        KMDMGPurchaseManager.manager.purchaseProduct(productIdentifier: productIdentifier, email: email, completion: completion)
#endif
    }
    
    func showStore() {
#if VERSION_DMG
        NSWorkspace.shared.open(URL(string: "\(KMLightMemberManager.manager.config.kStoreServerURL)/store/master")!)
#endif
    }
    
    func showPurchasesInfo() {
#if VERSION_DMG
        if KMLightMemberManager.manager.isLogin() {
            let token: String = KMLightMemberManager.manager.token.access_token
            NSWorkspace.shared.open(URL(string: "\(KMLightMemberManager.manager.config.kStoreServerURL)/account/master-subscription?appid=16&token=\(token)")!)
        }
#endif
    }
    
    func restorePurchases(_ completion: @escaping KMPurchaseRestoreCompletion) {
        KMPrint("准备restore")
#if VERSION_FREE
        KMPrint("正在restore")
        KMInAppPurchaseManager.manager.restorePurchases("", completion)
#endif
        
#if VERSION_DMG
        KMDMGPurchaseManager.manager.restorePurchases()
        KMPrint("正在restore DMG")
#endif
    }
    
    func checkSubscriptionStatus(_ completion: @escaping KMPurchaseCheckSubscriptionStatusCompletion) {
#if VERSION_FREE
        KMInAppPurchaseManager.manager.checkSubscriptionStatus(completion)
#endif
        
#if VERSION_DMG
        
#endif
    }
}