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

import PhotosUI

class TSEditLiveVC: TSBaseVC, UINavigationControllerDelegate {
    
    lazy var editLiveSectionModel: TSEditLiveSectionModel = {
        let section = TSEditLiveSectionModel()
        section.items = [TSEditLiveItemModel()]
        return section
    }()

    lazy var editLiveHistorySectionModel: TSImageDataSectionModel = {
        return kImageDataCenterShared.editLiveHistoryListArray.first!
    }()
    
    var dataArray:[Component] = [Component]()

    
    lazy var navBarView: TSBaseNavContentBarView = {
        let navBarView = TSBaseNavContentBarView()
        let titleImageView = UIImageView.createImageView(imageName: "nav_title_editlive",contentMode: .scaleToFill)
        
        navBarView.barView.addSubview(titleImageView)
        titleImageView.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.left.equalTo(16)
            make.width.equalTo(252)
            make.height.equalTo(24)
        }
        return navBarView
    }()

    
    lazy var collectionComponent: CollectionViewComponent = {
        let layout = UICollectionViewFlowLayout()
        let cp = CollectionViewComponent(frame: CGRect.zero, layout: layout, attributes: [ :])
        cp.collectionView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: k_Height_TabBar, right: 0)
        
        cp.itemActionHandler = { [weak self] cellCp, indexPath in
            guard let self = self else { return }
            self.openVideoPicker()
        }
        
        cp.itemDidSelectedHandler = { [weak self] (object, indexPath) in
            guard let self = self else { return }
            let obj = dataArray.safeObj(At: indexPath.section)
            if let liveModel = obj as? TSImageDataSectionModel {
                if liveModel.style == .homeLiveList{
                    let vc = TSLiveWallpaperBrowseVC(itemModels: liveModel.items,currentIndex: indexPath.row)
                    vc.isCanDelete = true
                    vc.deleteCompletion = {[weak self] item in
                        guard let self = self else { return }
                        if let itemModel = editLiveHistorySectionModel.items.safeObj(At: item) {
                            editLiveHistorySectionModel.items.remove(at: item)
                            TSFileManagerTool.removeItem(from: itemModel.imageUrl.fillCacheURL)
                            TSFileManagerTool.removeItem(from: itemModel.videoUrl.fillCacheURL)
                            kImageDataCenterShared.editLiveHistoryListArray = [editLiveHistorySectionModel]
                            reloadView()
                        }
                    }
                    kPresentModalVC(target: self, modelVC: vc)
                }
            }
        }

        return cp
    }()

    override func createView() {
        
        setViewBgImageNamed(named: "view_main_bg")
        
        navBarContentView.addSubview(navBarView)
        navBarView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        contentView.addSubview(collectionComponent.collectionView)
        collectionComponent.collectionView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        reloadView()
    }
    
    func reloadView(){
        collectionComponent.clear()
        if editLiveHistorySectionModel.items.count  > 0 {
            dataArray = [editLiveSectionModel,editLiveHistorySectionModel]
        }else{
            dataArray = [editLiveSectionModel]
        }
        collectionComponent.reloadView(with:dataArray)
    }
}

import UniformTypeIdentifiers
extension TSEditLiveVC: UIImagePickerControllerDelegate {
    func openVideoPicker() {
        TSToastShared.showLoading(in: self.view)
        let picker = UIImagePickerController()
        picker.sourceType = .photoLibrary
        picker.mediaTypes =  [UTType.movie.identifier] // 仅允许选择视频
        picker.allowsEditing = true // 启用编辑功能
        picker.delegate = self
        picker.videoMaximumDuration = 3.0
        present(picker, animated: true) {
            TSToastShared.hideLoading()
        }
    }
    // 用户完成选择
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
        
        TSToastShared.hideLoading()
        if let editedURL = info[.mediaURL] as? URL {
            debugPrint("Selected video: \(editedURL)")
            // 在这里处理选中的视频（例如上传或保存）

            let cachesDirectory = TSFileManagerTool.editLiveVideoPathURL
            let targetURL = cachesDirectory.appendingPathComponent("assemblePickerVideo").appendingPathExtension(editedURL.pathExtension)
            TSFileManagerTool.copyFileWithOverwrite(from: editedURL, to: targetURL)
            
            
//            LivePhotoUtil.convertVideo(targetURL.path) { success, msg in
//                debugPrint(msg)
//            }

//            LivePhotoConverter.convertVideo(targetURL) { success, image, video, msg in
//                debugPrint(msg)
//            }
  
            saveLive(videoPath: targetURL)
        }
        picker.dismiss(animated: true, completion: nil)
    }

    // 用户取消选择
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        TSToastShared.hideLoading()
        picker.dismiss(animated: true, completion: nil)
    }
}

extension TSEditLiveVC{
    
    func openVideoClipperVC(videoURL:URL) {
            let clipperController = GPVideoClipperController.clipperWithVideoURL(videoURL, makerBlock: { (maker) in
                maker.startTime = 0
                maker.endTime = 15
                maker.clippedVideoMinDuration = 1
                maker.clippedVideoMaxDuration = 3
                maker.leftSelectedImage = UIImage(named: "eidt_arrow_left")!
                maker.selectedBoxColor = .white
                maker.rightSelectedImage = UIImage(named: "eidt_arrow_right")!
                maker.leftMargin = 77
                maker.rightMargin = 37
                maker.selectedImageWidth = 14
            }) {[weak self] (videoURL, videoAsset, coverImage) in
                guard let self = self else { return }
                self.saveLive(videoPath: videoURL)
            }
        
        kPresentModalVC(target: self, modelVC: clipperController)
    }
    
    
    func saveLive(videoPath:URL){
        TSToastShared.showLoading()
        LivePhotoConverter.convertVideo(videoPath) { success, imageURL, videoURL, errorMsg in
            if success {
                debugPrint("Live Photo Saved,The live photo was successfully saved to Photos.")
                
                if let imageURL = imageURL,let videoURL = videoURL {
                    LivePhotoConverter.saveToLibrary(videoURL: videoURL, imageURL: imageURL) { success in
                        kSavePhotoSuccesswShared.show(atView: self.view,text: "DIY Successfully".localized)
                    }
                    
                    
                    let saveURL = TSFileManagerTool.saveLiveVideoPathURL
                    let timestampString = Date.timestampString
                    let saveImageURL = saveURL.appendingPathComponent("image\(timestampString).heic")
                    let saveVideoURL = saveURL.appendingPathComponent("video\(timestampString).mov")
                    TSFileManagerTool.copyFileWithOverwrite(from: imageURL, to: saveImageURL)
                    TSFileManagerTool.copyFileWithOverwrite(from: videoURL, to: saveVideoURL)
                    
                    
                    let itemModel = TSImageDataItemModel()
                    itemModel.imageUrl = TSFileManagerTool.getCacheSubPath(at: saveImageURL)!
                    itemModel.videoUrl = TSFileManagerTool.getCacheSubPath(at: saveVideoURL)!
                    self.editLiveHistorySectionModel.items.insert(itemModel, at: 0)
                    kImageDataCenterShared.editLiveHistoryListArray = [self.editLiveHistorySectionModel]
                    self.reloadView()
                }
            }else {
                debugPrint("Live Photo Not Saved,The live photo was not saved to Photos.")
            }
        }
        
        
        
        
//        let ts = Date().timeIntervalSince1970
//        let documentURL = TSFileManagerTool.documentsDirectory.appendingPathComponent("\(Int(ts)).mov")
//        let documentURL = TSFileManagerTool.documentsDirectory    
//        Converter4Video(path: videoPath.path).resizeVideo(at: videoPath.path, outputPath: documentURL.path, outputSize: CGSize(width: 1080, height: 1920)) { success, error in
//            guard success else{
//                debugPrint(error)
//                return
//            }
//         
//            LivePhoto.generate(from: nil, videoURL: documentURL) { progress in
//    
//            } completion: {[weak self] (livePhoto, resources) in
//                guard let self = self else { return }
//    
//                if let resources = resources {
//                    LivePhoto.saveToLibrary(resources, completion: { (success) in
//                        kExecuteOnMainThread {
//                            TSToastShared.hideLoading()
//                            if success {
//                                debugPrint("Live Photo Saved,The live photo was successfully saved to Photos.")
//                                kSavePhotoSuccesswShared.show(atView: self.view)
//                            }else {
//                                debugPrint("Live Photo Not Saved,The live photo was not saved to Photos.")
//                            }
//    
//                            TSFileManagerTool.removeItem(from: resources.pairedImage)
//                            TSFileManagerTool.removeItem(from: resources.pairedVideo)
//                        }
//                    })
//                }
//            }
//        }
        
//        LivePhoto.resizeVideoToFixedHeight(videoURL: videoPath, outputFolder: documentURL) { outputURL in
//            if let outputURL = outputURL {
//                print("Resized video saved to: \(outputURL)")
//                
//                LivePhoto.generate(from: nil, videoURL: outputURL) { progress in
//        
//                } completion: {[weak self] (livePhoto, resources) in
//                    guard let self = self else { return }
//        
//                    if let resources = resources {
//                        LivePhoto.saveToLibrary(resources, completion: { (success) in
//                            kExecuteOnMainThread {
//                                TSToastShared.hideLoading()
//                                if success {
//                                    debugPrint("Live Photo Saved,The live photo was successfully saved to Photos.")
//                                    kSavePhotoSuccesswShared.show(atView: self.view)
//                                }else {
//                                    debugPrint("Live Photo Not Saved,The live photo was not saved to Photos.")
//                                }
//        
//                                TSFileManagerTool.removeItem(from: resources.pairedImage)
//                                TSFileManagerTool.removeItem(from: resources.pairedVideo)
//                            }
//                        })
//                    }
//                }
//                
//            } else {
//                print("Failed to resize video.")
//            }
//        }
        
        
        


        
//        VideoRecorder.shared.saveLivePhoto(duration: 2.5, outputDirectory: TSFileManagerTool.saveLiveVideoPathURL) { [weak self] recordHandler in
//
////                    recordHandler?()
//        
//        } completion: { [weak self] videoURL, imageURL, errorMsg in
//            guard let self = self else { return }
////        }
////        LivePhotoCreater().saveLivePhoto(from: videoPath, outputDirectory: TSFileManagerTool.saveLiveVideoPathURL) { videoURL, imageURL, errorMsg in
//            if let imageURL = imageURL,let videoURL = videoURL {
//                LivePhotoConverter.saveToLibrary(videoURL: videoURL, imageURL: imageURL) { success in
//                    kSavePhotoSuccesswShared.show(atView: self.view)
//                }
//                
//                
//                let saveURL = TSFileManagerTool.saveLiveVideoPathURL
//                let timestampString = Date.timestampString
//                let saveImageURL = saveURL.appendingPathComponent("image\(timestampString).heic")
//                let saveVideoURL = saveURL.appendingPathComponent("video\(timestampString).mov")
//                TSFileManagerTool.copyFileWithOverwrite(from: imageURL, to: saveImageURL)
//                TSFileManagerTool.copyFileWithOverwrite(from: videoURL, to: saveVideoURL)
//                
//                
//                let itemModel = TSImageDataItemModel()
//                itemModel.imageUrl = TSFileManagerTool.getCacheSubPath(at: saveImageURL)!
//                itemModel.videoUrl = TSFileManagerTool.getCacheSubPath(at: saveVideoURL)!
//                self.editLiveHistorySectionModel.items.append(itemModel)
//                kImageDataCenterShared.editLiveHistoryListArray = [self.editLiveHistorySectionModel]
//                self.reloadView()
//            }
//        }
    }
    
//    func saveLivePhotoVideoRecorder(){
//        
//        
//        VideoRecorder.shared.saveLivePhoto(duration: 3.0, outputDirectory: TSFileManagerTool.saveLiveVideoPathURL) { [weak self] recordHandler in
//
////                    recordHandler?()
//        
//        } completion: { [weak self] videoURL, imageURL, errorMsg in
//            guard let self = self else { return }
////        }
////        LivePhotoCreater().saveLivePhoto(from: videoPath, outputDirectory: TSFileManagerTool.saveLiveVideoPathURL) { videoURL, imageURL, errorMsg in
//            if let imageURL = imageURL,let videoURL = videoURL {
//                LivePhotoConverter.saveToLibrary(videoURL: videoURL, imageURL: imageURL) { success in
//                    kSavePhotoSuccesswShared.show(atView: self.view)
//                }
//                
//                
//                let saveURL = TSFileManagerTool.saveLiveVideoPathURL
//                let timestampString = Date.timestampString
//                let saveImageURL = saveURL.appendingPathComponent("image\(timestampString).heic")
//                let saveVideoURL = saveURL.appendingPathComponent("video\(timestampString).mov")
//                TSFileManagerTool.copyFileWithOverwrite(from: imageURL, to: saveImageURL)
//                TSFileManagerTool.copyFileWithOverwrite(from: videoURL, to: saveVideoURL)
//                
//                
//                let itemModel = TSImageDataItemModel()
//                itemModel.imageUrl = TSFileManagerTool.getCacheSubPath(at: saveImageURL)!
//                itemModel.videoUrl = TSFileManagerTool.getCacheSubPath(at: saveVideoURL)!
//                self.editLiveHistorySectionModel.items.append(itemModel)
//                kImageDataCenterShared.editLiveHistoryListArray = [self.editLiveHistorySectionModel]
//                self.reloadView()
//            }
//        }
//    }
}





















// MARK: - PHPickerViewControllerDelegate
//extension TSEditLiveVC: PHPickerViewControllerDelegate {
//
//    /// Present `PHPickerViewController`
//    func pick(_ filter: PHPickerFilter) {
//        var config = PHPickerConfiguration()
//        config.filter = filter
//        config.selectionLimit = 1
//        config.preferredAssetRepresentationMode = .current
//        let picker = PHPickerViewController(configuration: config)
//        picker.delegate = self
//        picker.modalPresentationStyle = .overFullScreen
//        present(picker, animated: true, completion: nil)
//    }
//
//    func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
//        defer { picker.dismiss(animated: true) }
//        assemblePicker(picker, didFinishPicking: results)
//    }
//
//    func assemblePicker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
//        guard let itemProvider = results.first?.itemProvider else {
//            return
//        }
//
//        if itemProvider.hasItemConformingToTypeIdentifier(UTType.movie.identifier) {
//            itemProvider.loadFileRepresentation(forTypeIdentifier: itemProvider.registeredTypeIdentifiers.first!) { [weak self] url, error in
//                guard let self, let url = url else {
//                    return
//                }
//                do {
//                    let cachesDirectory = try self.cachesDirectory()
//                    let targetURL = cachesDirectory.appendingPathComponent("assemblePickerVideo").appendingPathExtension(url.pathExtension)
//                    let fileManager = FileManager.default
//                    // 如果目标路径存在同名文件，先删除旧文件
//                    if fileManager.fileExists(atPath: targetURL.path) {
//                        try fileManager.removeItem(at: targetURL)
//                    }
//
//                    try fileManager.copyItem(at: url, to: targetURL)
//
//                    kExecuteOnMainThread {
//                        self.openVideoClipperVC(videoURL: targetURL)
//                    }
//
//                } catch {
//                    TSToastShared.showToast(message: "An error occurred")
//                }
//            }
//        }
//    }
//
//    private func cachesDirectory() throws -> URL {
//        let cachesDirectoryURL = try FileManager.default.url(for: .cachesDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
//        let cachesDirectory = cachesDirectoryURL.appendingPathComponent("asemble", isDirectory: true)
//        if !FileManager.default.fileExists(atPath: cachesDirectory.absoluteString) {
//            try FileManager.default.createDirectory(at: cachesDirectory, withIntermediateDirectories: true, attributes: nil)
//        }
//        return cachesDirectory
//    }
//}



