//
//  SecretPhotoManager.swift
//  PhoneManager
//
//  Created by edy on 2025/5/26.
//

import Foundation
import UIKit
import HXPhotoPicker
import CryptoKit
import Photos


class SecretPhotoManager: NSObject, PhotoPickerControllerDelegate , CameraControllerDelegate {

    func cameraController(_ cameraController: HXPhotoPicker.CameraController, didFinishWithResult result: HXPhotoPicker.CameraController.Result, phAsset: PHAsset?, location: CLLocation?) {
        switch result {
        case .image(let image):
            image.compressImage(0.3) {[weak self] image in
                let data = image.pngData()
                guard self?.callback != nil else { return }
                self?.callback!(0,data)
            }
            break
        case .video(let fileUrl):
            let data = NSData(contentsOf: fileUrl)
            guard callback != nil else { return }
            callback!(1,data)
            break
        default:
            break
        }
    }

    func pickerController(_ pickerController: PhotoPickerController, didFinishSelection result: PickerResult) {
        guard callback != nil else { return }
        callback!(-1,result.photoAssets)
    }


    func deleteAssets(_ assets:[PHAsset] = []) -> Void {
        if assets.count > 0 {
            PMLoadingHUD.share.show()
            PHPhotoLibrary.shared().performChanges({
                PHAssetChangeRequest.deleteAssets(assets as NSFastEnumeration)
            }) { success, error in

                if success {
                    print("删除成功")
                    DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
                        PMLoadingHUD.share.disMiss()
                    }
                } else if let error = error {
                    DispatchQueue.main.async {
                        PMLoadingHUD.share.disMiss()
                    }
                    print("删除失败: \(error.localizedDescription)")
                }


            }
        }
    }

    static let share = SecretPhotoManager()

    var callback:((Int,Any)->Void)?

    func show(_ type:Int) -> Void {
        if type == 0 {
            let config = CameraConfiguration()
            let vc = CameraController(config: config, type: .all, delegate: self)
            vc.modalPresentationStyle = .overFullScreen
            guard let root = cWindow?.rootViewController else { return }
            root.present(vc, animated: true)
        }else{
            var config = PickerConfiguration()
            config.selectMode = .multiple
            config.maximumSelectedCount = 4
            let vc = PhotoPickerController(picker: config, delegate: self)
            vc.modalPresentationStyle = .overFullScreen
            guard let root = cWindow?.rootViewController else { return }
            root.present(vc, animated: true)
        }
    }
}
