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

import PhotosUI

class TSEditLiveVC: TSBaseVC, UINavigationControllerDelegate {
    
    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
    }()

    var editLiveHistoryListArray:[TSImageDataSectionModel] = kImageDataCenterShared.editLiveHistoryListArray
    
    override func createView() {
        
        setViewBgImageNamed(named: "view_main_bg")
        
        navBarContentView.addSubview(navBarView)
        navBarView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        let videoUpImageView = UIImageView.createImageView(imageName: "video_up")
        contentView.addSubview(videoUpImageView)
        videoUpImageView.snp.makeConstraints { make in
            make.top.equalTo(130)
            make.centerX.equalToSuperview()
            make.width.height.equalTo(153)
        }
        
        let videoText = UILabel.createLabel(text: "Upload Video".localized,font: UIFont.systemFont(ofSize: 16, weight: .medium),textColor: .white,textAlignment: .center)
        contentView.addSubview(videoText)
        videoText.snp.makeConstraints { make in
            make.leading.equalTo(16)
            make.trailing.equalTo(-16)
            make.top.equalTo(videoUpImageView.snp.bottom).offset(12)
            make.height.equalTo(16)
        }
        
        let diyBtn: UIButton = TSViewTool.createNormalSubmitBtn(title: "DIY Live Wallpaper".localized, imageNamed: "edit_black") { [weak self]  in
            guard let self = self else { return }
            self.pick(.any(of: [.videos]))
        }
        
        diyBtn.cornerRadius = 30
        contentView.addSubview(diyBtn)
        diyBtn.snp.makeConstraints { make in
            make.leading.equalTo(16)
            make.trailing.equalTo(-16)
            make.top.equalTo(videoText.snp.bottom).offset(53)
            make.height.equalTo(60)
        }
    }
    
    
    func saveLive(videoPath:URL){
        
        TSToastShared.showLoading()
        
        LivePhoto.generate(from: nil, videoURL: videoPath) { 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)
                    }
                })
            }
        }
    }
}


// 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
    }
}

//import UniformTypeIdentifiers
//extension TSEditLiveVC: UIImagePickerControllerDelegate {
//    func openVideoPicker() {
//        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, completion: nil)
//    }
//    // 用户完成选择
//    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
//        if let editedURL = info[.mediaURL] as? URL {
//            debugPrint("Selected video: \(editedURL)")
//            // 在这里处理选中的视频（例如上传或保存）
//            saveLive(videoPath: editedURL)
//        }
//        picker.dismiss(animated: true, completion: nil)
//    }
//
//    // 用户取消选择
//    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
//        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)
    }
}


