//
//  PlayContoller7.swift
//  tdvideo
//
//  Created by mac on 2024/2/10.
//

import UIKit
import AVFoundation
import MobileCoreServices
import CoreImage
import ImageIO
import Photos

class PlayContoller7: UIViewController {
    
    var startRecordingButton:UIButton?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.brown
        
        setupUI()
//        bbb()
//        aaa()
    }
    
    private func setupUI() {
        startRecordingButton = UIButton(type: .system)
        startRecordingButton?.setTitle("开始合成空间图片", for: .normal)
        startRecordingButton?.setTitleColor(UIColor.white, for: UIControl.State.normal)
        startRecordingButton?.addTarget(self, action: #selector(toggleRecording(_:)), for: .touchUpInside)
        startRecordingButton?.frame = CGRect(x: 0, y: view.frame.size.height - 250, width: view.frame.size.width, height: 50)
        view.addSubview(startRecordingButton!)
    }
    
    @objc private func toggleRecording(_ sender: UIButton) {
        
        bbb()
    }
    
    func bbb(){
        let img1:UIImage = UIImage(named: "a.HEIC")!
        let img2:UIImage = UIImage(named: "b.HEIC")!
        
        let imageSize1 = CGRect(x: 0, y: 0, width: img1.cgImage!.width, height: img1.cgImage!.height)
        let imageSize2 = CGRect(x: 0, y: 0, width: img2.cgImage!.width, height: img2.cgImage!.height)
        
       let url =   URL.documentsDirectory.appending(path:"aaa12.HEIC")
      
        let destination = CGImageDestinationCreateWithURL(url as CFURL, UTType.heic.identifier as CFString, 2, nil)!

        //左眼 --- 参数大于16.0 --- 配置普通图片转成左眼空间图片的参数
        /*
         [ColorModel: RGB, ProfileName: sRGB IEC61966-2.1, Depth: 8, {TIFF}: {
             Orientation = 1;
             TileLength = 512;
             TileWidth = 512;
         }, {HEIF}: {
             CameraExtrinsics =     {
                 CoordinateSystemID = 0;
                 Position =         (
                     "-0.019238",
                     0,
                     0
                 );
                 Rotation =         (
                     1,
                     0,
                     0,
                     0,
                     1,
                     0,
                     0,
                     0,
                     1
                 );
             };
         }, PixelWidth: 4032, PixelHeight: 3024, Orientation: 1]
         
         */
        
        let properties1 = [
            kCGImagePropertyGroups: [
                kCGImagePropertyGroupIndex: 0,
                kCGImagePropertyGroupType: kCGImagePropertyGroupTypeStereoPair,
                kCGImagePropertyGroupImageIndexLeft: 0,
                kCGImagePropertyGroupImageIndexRight: 1,
                
            ],
            kCGImagePropertyHEIFDictionary: [
                kIIOMetadata_CameraExtrinsicsKey: [
                    kIIOCameraExtrinsics_CoordinateSystemID: 0,
                    kIIOCameraExtrinsics_Position: [
                        0,
                        0,
                        0
                    ],
                    kIIOCameraExtrinsics_Rotation: [
                        1, 0, 0,
                        0, 1, 0,
                        0, 0, 1
                    ]
                ]
            ]
        ]
        //右眼
        let properties2 = [
            kCGImagePropertyGroups: [
                kCGImagePropertyGroupIndex: 0,
                kCGImagePropertyGroupType: kCGImagePropertyGroupTypeStereoPair,
                kCGImagePropertyGroupImageIndexLeft: 0,
                kCGImagePropertyGroupImageIndexRight: 1,
            ],
            kCGImagePropertyHEIFDictionary: [
                kIIOMetadata_CameraExtrinsicsKey: [
                    kIIOCameraExtrinsics_CoordinateSystemID: 0,
                    kIIOCameraExtrinsics_Position: [
                        -0.019238,
                        0,
                        0
                    ],
                    kIIOCameraExtrinsics_Rotation: [
                        1, 0, 0,
                        0, 1, 0,
                        0, 0, 1
                    ]
                ]
            ]
        ]
        
        let leftImg = fixOrientation(img1)
        let rightImg = fixOrientation(img2)
        
        CGImageDestinationAddImage(destination, leftImg.cgImage!, properties1 as CFDictionary)
        CGImageDestinationAddImage(destination, rightImg.cgImage!, properties2 as CFDictionary)
        CGImageDestinationFinalize(destination)
        
        let image = UIImage(contentsOfFile: url.path())
        let source = CGImageSourceCreateWithURL(url as CFURL, nil)!
        guard let properties22 = CGImageSourceCopyPropertiesAtIndex(source, 1, nil) as? [CFString: Any] else {
                return 
        }
        print(properties22)
        
        savePhoto(url)
        
    }
    
    func aaa() {
        let imageSize = CGRect(x: 0, y: 0, width: 3072, height: 3072)
        let leftImage = CIContext().createCGImage(.red, from: imageSize)!
        let rightImage = CIContext().createCGImage(.blue, from: imageSize)!
        
        let url = URL.documentsDirectory.appendingPathComponent("33122.HEIC")
        print("URL: \(url)")

        let destination = CGImageDestinationCreateWithURL(url as CFURL, UTType.heic.identifier as CFString, 2, nil)!
        
        let properties1 = [
            kCGImagePropertyGroups: [
                kCGImagePropertyGroupIndex: 0,
                kCGImagePropertyGroupType: kCGImagePropertyGroupTypeStereoPair,
                kCGImagePropertyGroupImageIndexLeft: 0,
                kCGImagePropertyGroupImageIndexRight: 1
            ],
            kCGImagePropertyHEIFDictionary: [
                kIIOMetadata_CameraExtrinsicsKey: [
                    kIIOCameraExtrinsics_CoordinateSystemID: 0,
                    kIIOCameraExtrinsics_Position: [
                        0,
                        0,
                        0
                    ],
                    kIIOCameraExtrinsics_Rotation: [
                        1, 0, 0,
                        0, 1, 0,
                        0, 0, 1
                    ]
                ]
            ]
        ]
        
        let properties2 = [
            kCGImagePropertyGroups: [
                kCGImagePropertyGroupIndex: 0,
                kCGImagePropertyGroupType: kCGImagePropertyGroupTypeStereoPair,
                kCGImagePropertyGroupImageIndexLeft: 0,
                kCGImagePropertyGroupImageIndexRight: 1
                
            ],
            kCGImagePropertyHEIFDictionary: [
                kIIOMetadata_CameraExtrinsicsKey: [
                    kIIOCameraExtrinsics_CoordinateSystemID: 0,
                    kIIOCameraExtrinsics_Position: [
                        -0.019238,
                        0,
                        0
                    ],
                    kIIOCameraExtrinsics_Rotation: [
                        1, 0, 0,
                        0, 1, 0,
                        0, 0, 1
                    ]
                ]
            ]
        ]
        
        //图片合成的方向回正
        CGImageDestinationAddImage(destination, leftImage, properties1 as CFDictionary)
        CGImageDestinationAddImage(destination, rightImage, properties2 as CFDictionary)
        CGImageDestinationFinalize(destination)
        
        // 检查 imageSource 是否为 nil
        guard let imageSource = CGImageSourceCreateWithURL(url as CFURL, nil) else {
            print("Failed to create CGImageSource")
            return
        }
        
        // 使用可选绑定来安全地解包 properties
        if let properties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, nil) as? [CFString: Any] {
            print(properties)
        } else {
            print("Failed to retrieve properties")
        }
        
        let image = UIImage(contentsOfFile: url.path)
        savePhoto(url)
    }
    
    func savePhoto(_ fileURL: URL) {
        
        // 创建 PHAssetCreationRequest
        PHPhotoLibrary.shared().performChanges({
            let creationRequest = PHAssetCreationRequest.forAsset()
            creationRequest.addResource(with: .photoProxy, fileURL: fileURL, options: nil)
                
        }) { success, error in
            if let error = error {
                print("Error saving photo to library: \(error.localizedDescription)")
            } else {
                print("Photo saved to library successfully.")
            }
        }
    }

    //修正图片的方向
    func fixOrientation(_ image: UIImage) -> UIImage {
        // No-op if the orientation is already correct
        guard image.imageOrientation != .up else { return image }
        
        // We need to calculate the proper transformation to make the image upright.
        // We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.
        var transform = CGAffineTransform.identity
        
        switch image.imageOrientation {
        case .down, .downMirrored:
            transform = transform.translatedBy(x: image.size.width, y: image.size.height)
            transform = transform.rotated(by: .pi)
        case .left, .leftMirrored:
            transform = transform.translatedBy(x: image.size.width, y: 0)
            transform = transform.rotated(by: .pi / 2)
        case .right, .rightMirrored:
            transform = transform.translatedBy(x: 0, y: image.size.height)
            transform = transform.rotated(by: -.pi / 2)
        default:
            break
        }
        
        switch image.imageOrientation {
        case .upMirrored, .downMirrored:
            transform = transform.translatedBy(x: image.size.width, y: 0)
            transform = transform.scaledBy(x: -1, y: 1)
        case .leftMirrored, .rightMirrored:
            transform = transform.translatedBy(x: image.size.height, y: 0)
            transform = transform.scaledBy(x: -1, y: 1)
        default:
            break
        }
        
        // Now we draw the underlying CGImage into a new context, applying the transform
        // calculated above.
        guard let cgImage = image.cgImage,
              let colorSpace = cgImage.colorSpace,
              let context = CGContext(data: nil,
                                      width: Int(image.size.width),
                                      height: Int(image.size.height),
                                      bitsPerComponent: cgImage.bitsPerComponent,
                                      bytesPerRow: 0,
                                      space: colorSpace,
                                      bitmapInfo: cgImage.bitmapInfo.rawValue)
        else {
            return image
        }
        
        context.concatenate(transform)
        
        switch image.imageOrientation {
        case .left, .leftMirrored, .right, .rightMirrored:
            // Grr...
            context.draw(cgImage, in: CGRect(x: 0, y: 0, width: image.size.height, height: image.size.width))
        default:
            context.draw(cgImage, in: CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height))
        }
        
        // And now we just create a new UIImage from the drawing context
        guard let cgImageFixed = context.makeImage() else { return image }
        let fixedImage = UIImage(cgImage: cgImageFixed)
        return fixedImage
    }

    
}
