//
//  TSCommonTool.swift
//  TSLiveWallpaper
//
//  Created by 100Years on 2024/12/20.
//

import Kingfisher
import Foundation

/// 主线程延迟执行回调
/// - Parameters:
///   - delay: 延迟时间（秒）
///   - completion: 延迟后的回调
func kMainAfter(_ delay: TimeInterval, completion: @escaping () -> Void) {
    DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
        completion()
    }
}

func kMainShort(completion: @escaping () -> Void) {
    DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
        completion()
    }
}

/// 在主线程上执行代码
/// - Parameter block: 要执行的代码块
func kMainAsync(_ block: @escaping () -> Void) {
    DispatchQueue.main.async {
        block()
    }
}

let kAppName:String = "Old Photo"
let kUploadImageMaxBit10Size:Int = 10 * 1024 * 1024 //10M
let kUploadImageMaxBit5Size:Int = 5 * 1024 * 1024 //5M


func kShareContent(target: UIViewController,anyData:Any) {
    let text = "Turn yourself into a Ghibli style with AI magic! 🎨✨ This app creates stunning anime, cyberpunk & more—just upload a photo. Try it now!"
    kShareContent(target: target, anyData: anyData, text: text)
}

func kShareContent(target: UIViewController,anyData:Any?,text:String?) {
//    let urlString = "https://apps.apple.com/app/id\(appid)"
    var activityItems:[Any] = []

    if let anyData = anyData {
        activityItems.append(anyData)
    }
    
//    if let text = text {
//        activityItems.append(text+"\nApp:"+urlString)
//    }
//    
//    if let url = URL(string: "https://apps.apple.com/app/id\(appid)") {
//        activityItems.append(url)
//    }
    
    if activityItems.isEmpty {
        return
    }

    let vc = UIActivityViewController(activityItems: activityItems, applicationActivities: nil)
    vc.completionWithItemsHandler = { activity,completed, returnedItems, error in
        switch activity {
        case .copyToPasteboard:
            UIPasteboard.general.string = text
        case .saveToCameraRoll:
            dePrint("保存到了相册")
            kSaveSuccesswShared.show(atView:target.view)
            
            if completed{
                TSSetingVM.kFirstSaveRateAction()
            }else {  // 用户取消分享
                if let error = error {
                    dePrint("分享失败: \(error.localizedDescription)")
                } else {
                    dePrint("用户取消分享")
                }
            }
        
        default:
            dePrint("")
        }
    }

    if UIDevice.current.userInterfaceIdiom == .pad {
        vc.modalPresentationStyle = .popover
        vc.popoverPresentationController?.sourceView = target.view
        vc.popoverPresentationController?.sourceRect = target.view.bounds
    }
    
    target.present(vc, animated: true)
}
