//
//  Reporter.swift
//  xray
//
//  Created by Anton Kononenko on 7/23/20.
//  Copyright © 2020 Applicaster. All rights reserved.
//

import Foundation
import MessageUI

public protocol StorableSinkDelegate {
    func getLogFileUrl() async -> URL?
    func deleteLogFile() async
    @MainActor func getDefaultContexts() -> [String: String]?
}

public class Reporter {
    public static let sharedInstance = Reporter()
    public private(set) static var sharedEmails: [String]?
    public private(set) static var sharedLogFileSinkDelegate: StorableSinkDelegate?
    var email = Email()

    public static func setDefaultData(emails: [String],
                                      logFileSinkDelegate: StorableSinkDelegate?) {
        sharedEmails = emails
        sharedLogFileSinkDelegate = logFileSinkDelegate
    }

    @MainActor
    public static func requestSendEmail() async {
        guard let sharedEmails else {
            print("Cannot send email, at least one sender must be defined")
            return
        }

        guard sharedInstance.email.canSendMail() else {
            presentAlertUnableToSendMail()
            return
        }

        guard let url = await sharedLogFileSinkDelegate?.getLogFileUrl() else {
            presentAlertNoLogFileToSend()
            return
        }

        await sharedInstance.email.requestSendEmail(emails: sharedEmails,
                                                    sharedFileURL: url,
                                                    contexts: contexts,
                                                    attachments: nil)
        await sharedLogFileSinkDelegate?.deleteLogFile()
    }

    @MainActor
    static func presentAlertUnableToSendMail() {
        let alert = UIAlertController(title: "Cannot send email", message: "Please check if your device has email configured", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
        alert.view.tintColor = .darkGray

        sharedInstance.email.presentController(vc: alert)
    }

    @MainActor
    static func presentAlertNoLogFileToSend() {
        let alert = UIAlertController(title: "Unable to export", message: "No logs are defined for export, please check log level settings", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
        alert.view.tintColor = .darkGray

        sharedInstance.email.presentController(vc: alert)
    }

    @MainActor
    static var contexts: [String: Any]? {
        sharedLogFileSinkDelegate?.getDefaultContexts()
    }
}
