//
//  EmailService.swift
//  LeCountdown
//
//  Created by Laurent Morvillier on 14/03/2023.
//

import Foundation
import MessageUI
import SwiftUI

struct MailView: UIViewControllerRepresentable {

    @Binding var isShowing: Bool
//    @Binding var result: Result<MFMailComposeResult, Error>?

    class Coordinator: NSObject, MFMailComposeViewControllerDelegate {

        @Binding var isShowing: Bool
//        @Binding var result: Result<MFMailComposeResult, Error>?

        init(isShowing: Binding<Bool>) {
            _isShowing = isShowing
//            _result = result
        }

        func mailComposeController(_ controller: MFMailComposeViewController,
                                   didFinishWith result: MFMailComposeResult,
                                   error: Error?) {
            isShowing = false
            
//            guard error == nil else {
//                self.result = .failure(error!)
//                return
//            }
//            self.result = .success(result)
        }
    }

    func makeCoordinator() -> Coordinator {
        return Coordinator(isShowing: $isShowing)
    }

    func makeUIViewController(context: UIViewControllerRepresentableContext<MailView>) -> MFMailComposeViewController {
        let vc = MFMailComposeViewController()
        vc.mailComposeDelegate = context.coordinator
        vc.setSubject(Bundle.main.applicationName)
        vc.setToRecipients(["laurent@staxriver.com"])
        return vc
    }

    func updateUIViewController(_ uiViewController: MFMailComposeViewController,
                                context: UIViewControllerRepresentableContext<MailView>) {

    }
    
}

fileprivate extension Bundle {
    var applicationName: String {
        if let displayName: String = self.infoDictionary?["CFBundleDisplayName"] as? String {
            return displayName
        } else if let name: String = self.infoDictionary?["CFBundleName"] as? String {
            return name
        }
        return ""
    }
}
