import SwiftUI
import AVFoundation

struct Imagepicker : UIViewControllerRepresentable {
    @Binding var show: Bool
    @Binding var image: Data
    var sourceType: UIImagePickerController.SourceType
    var preset: ImageQualityPreset

    func makeCoordinator() -> Coordinator {
        return Coordinator(parent: self)
    }

    func makeUIViewController(context: UIViewControllerRepresentableContext<Imagepicker>) -> UIImagePickerController {
        let controller = UIImagePickerController()
        controller.sourceType = sourceType
        controller.delegate = context.coordinator
//        controller.mediaTypes = ["public.image", "public.movie"]
//        controller.videoQuality = .type640x480
        return controller
    }

    func updateUIViewController(_ uiViewController: UIImagePickerController, context: UIViewControllerRepresentableContext<Imagepicker>) {
    }

    class Coordinator: NSObject,UIImagePickerControllerDelegate,UINavigationControllerDelegate {
        var parent : Imagepicker
        var selectedPreset : VideoQualityPreset = .medium

        init(parent : Imagepicker){
            self.parent = parent
        }

        //MARK: - Cancel
        func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
            self.parent.show.toggle()
        }

        //MARK: - Use Photo / Movie
        func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
            if let image = info[.originalImage] as? UIImage {
                //MARK: - 画像データのリサイズ
                DispatchQueue.global(qos: .userInitiated).async {
                    // リサイズ処理
                    let scale: CGFloat = min(0.1, max(self.parent.preset.scale, 1.0))
                    if let resizedImage = image.resized(to: scale),
                       let data = resizedImage.jpegData(compressionQuality: self.parent.preset.compressionQuality) {
                        DispatchQueue.main.async {
                            self.parent.image = data
                            self.parent.show.toggle()
                        }
                    } else {
                        DispatchQueue.main.async {
                            print(debug: "Failed to resize or compress image")
                            self.parent.show.toggle()
                        }
                    }
                }
            } else if let videoURL = info[.mediaURL] as? URL {
                //MARK: - 動画データのリサイズ
                compressVideo(inputURL: videoURL, preset: selectedPreset) { compressedData in
                    DispatchQueue.main.async {
                        if let data = compressedData {
                            self.parent.image = data
                        } else {
                            print(debug: "Failed to compress video")
                        }
                        self.parent.show.toggle()
                    }
                }
            } else {
                DispatchQueue.main.async {
                    print(debug: "No valid media selected")
                    self.parent.show.toggle()
                }
            }
        }
    }
}
