//
//  CCSpatialShootController+GenerateImage.swift
//  SwiftProject
//
//  Created by aaa on 2024/5/22.
//

import Foundation
import AVFoundation
import Photos
import AVKit
import VideoToolbox
import SVProgressHUD
import Firebase
import CoreMotion

extension CCSpatialShootController {
    
    
    
    //合成空间图片
    func compositeSpatialPhoto(){
        let img1:UIImage = imgs[0] as! UIImage
        let img2:UIImage = imgs[1] as! UIImage

        let url =   URL.documentsDirectory.appending(path:"aaa12.HEIC")
        let destination = CGImageDestinationCreateWithURL(url as CFURL, UTType.heic.identifier as CFString, 2, nil)!
        var oo = imageCGImagePropertyOrientation.rawValue
//        let orientation_cf = CFNumberCreate(nil, CFNumberType.intType, &oo)
        let properties1 = [
            kCGImagePropertyGroups: [
                kCGImagePropertyGroupIndex: 0,
                kCGImagePropertyGroupType: kCGImagePropertyGroupTypeStereoPair,
                kCGImagePropertyGroupImageIndexLeft: 0,
                kCGImagePropertyGroupImageIndexRight: 1,
            ],
//            kCGImagePropertyTIFFDictionary:[
//                kCGImagePropertyOrientation:orientation_cf,
//            ],
//
//            kCGImagePropertyOrientation:orientation_cf as Any,
            kCGImagePropertyHEIFDictionary: [
                kIIOMetadata_CameraExtrinsicsKey: [
                    kIIOCameraExtrinsics_CoordinateSystemID: 0,
                    kIIOCameraExtrinsics_Position: [
                        0,
                        0,
                        0
                    ],
                    kIIOCameraExtrinsics_Rotation: [
                        1, 0, 0,
                        0, 1, 0,
                        0, 0, 1
                    ]
                ]
            ]
        ] as [CFString : Any]
        let properties2 = [
            kCGImagePropertyGroups: [
                kCGImagePropertyGroupIndex: 0,
                kCGImagePropertyGroupType: kCGImagePropertyGroupTypeStereoPair,
                kCGImagePropertyGroupImageIndexLeft: 0,
                kCGImagePropertyGroupImageIndexRight: 1,
            ],
//            kCGImagePropertyTIFFDictionary:[
//                kCGImagePropertyOrientation:orientation_cf,
//            ],
//            kCGImagePropertyOrientation:orientation_cf as Any,
            
            kCGImagePropertyHEIFDictionary: [
                kIIOMetadata_CameraExtrinsicsKey: [
                    kIIOCameraExtrinsics_CoordinateSystemID: 0,
                    kIIOCameraExtrinsics_Position: [
                        -0.019238,
                         0,
                         0
                    ],
                    kIIOCameraExtrinsics_Rotation: [
                        1, 0, 0,
                        0, 1, 0,
                        0, 0, 1
                    ]
                ]
            ]
        ] as [CFString : Any]
        
        let leftImg = img1//fixOrientation(img1)
        let rightImg = img2//fixOrientation(img2)
        
        

        let p_dic1:CFDictionary =  properties1 as CFDictionary
        CGImageDestinationAddImage(destination, leftImg.cgImage!,p_dic1)
        let p_dic2:CFDictionary =  properties2 as CFDictionary
        CGImageDestinationAddImage(destination, rightImg.cgImage!, p_dic2)

        let rr = CGImageDestinationFinalize(destination)
        if rr == false {
            print("ee..")
        }
        savePhoto(url)
        
    }
    
    
    
    
    //保存照片
    func savePhoto(_ fileURL: URL) {
        
        // 创建 PHAssetCreationRequest
        PHPhotoLibrary.shared().performChanges({
            let creationRequest = PHAssetCreationRequest.forAsset()
            creationRequest.addResource(with: .photoProxy, fileURL: fileURL, options: nil)
            
        }) {[weak self] success, error in
            
            DispatchQueue.main.async {
                SVProgressHUD.dismiss()
                print("SVProgressHUD.dismiss..1111.....")
            }
            
            if let error = error {
                print("Error saving photo to library: \(error.localizedDescription)")
                DispatchQueue.main.async {
                    SVProgressHUD.showInfo(withStatus: "\(NSLocalizedString("空间图片保存失败", comment: "")): \(error.localizedDescription)")
                }
            } else {
                print("Photo saved to library successfully.")
                DispatchQueue.main.async {
                    self?.getAlbumFirstPhoto()
                }
            }
        }
    }
    
}
