//
//  TSSetingViewModel.swift
//  AIEmoji
//
//  Created by 100Years on 2025/1/16.
//

import StoreKit

class TSSetingViewModel: ObservableObject {
    
    @Published var settingTypes: [SettingType] = SettingType.allCases
    
    // todo.kailen-privacy
    func showPrivacy(parent: UIViewController) {
        let vc = TSBusinessWebVC(urlType: .privacy)
        vc.hidesBottomBarWhenPushed = true
        parent.navigationController?.pushViewController(vc, animated: true)
    }

    // todo.kailen-Agreement
    func showAgreement(parent: UIViewController) {
        let vc = TSBusinessWebVC(urlType: .privacy)
        vc.hidesBottomBarWhenPushed = true
        parent.navigationController?.pushViewController(vc, animated: true)
    }

    // todo.kailen-logo
    func shareApp(parent: UIViewController) {
        let httpAppStoreLink = "https://apps.apple.com/app/id\(TSConfig.appid)"
        let text = ""
        let url = URL(string: httpAppStoreLink)!
        let image = UIImage(named: "App-Icon")!
        let vc = UIActivityViewController(activityItems: [image, text, url], applicationActivities: nil)
        vc.completionWithItemsHandler = { activity, value, _, error in
            if let type = activity, type == .copyToPasteboard {
                UIPasteboard.general.string = httpAppStoreLink
            }
        }
    
        if UIDevice.isPad {
            if let popover = vc.popoverPresentationController {
                popover.sourceView = parent.view // 设置锚点视图
                popover.sourceRect = CGRect(x: parent.view.bounds.midX, y: parent.view.bounds.midY, width: 0, height: 0) // 设置弹窗位置为屏幕中心
                popover.permittedArrowDirections = [] // 禁止箭头指向
            }
        }
        parent.present(vc, animated: true)
    }
    
    func rateAction() {
        let countKey = "ProcessCompletedCountKey"
        // If the app doesn't store the count, this returns 0.
        var count = UserDefaults.standard.integer(forKey: countKey)
        count += 1
        UserDefaults.standard.set(count, forKey: countKey)
        /// 如果当前版本 弹过一次 那么下一次就走url
        /// 如果当前版本 没弹过，那就弹
        if count >= 4 {
            let openStr = "itms-apps://itunes.apple.com/app/\(TSConfig.appid)?action=write-review"
            if let url = URL(string: openStr), UIApplication.shared.canOpenURL(url) {
                if #available(iOS 10.0, *) {
                    UIApplication.shared.open(url, options: [:], completionHandler: nil)
                } else {
                    UIApplication.shared.canOpenURL(url)
                }
            } else {
                print("链接出错")
            }
        } else {
            SKStoreReviewController.requestReview()
        }
    }
    
    // todo.kailen-logo
    func pushTutorials(parent: UIViewController) {

    }
}
