import UIKit
import TigaseSwift

// FIXME: solve linter suppressed issues
// swiftlint: disable force_unwrapping
class CertificateErrorAlert {
    public static func create(domain: String, certData: SslCertificateInfo, onAccept: (() -> Void)?, onDeny: (() -> Void)?) -> UIAlertController {
        return create(domain: domain, certName: certData.details.name, certHash: certData.details.fingerprintSha1, issuerName: certData.issuer?.name, issuerHash: certData.issuer?.fingerprintSha1, onAccept: onAccept, onDeny: onDeny)
    }

    public static func create(domain: String, certName: String, certHash: String, issuerName: String?, issuerHash: String?, onAccept: (() -> Void)?, onDeny: (() -> Void)?) -> UIAlertController {
        let issuer = issuerName != nil ? "\nissued by\n\(issuerName!)\n with fingerprint\n\(issuerHash!)" : ""
        let alert = UIAlertController(title: "Certificate issue", message: "Server for domain \(domain) provided invalid certificate for \(certName)\n with fingerprint\n\(certHash)\(issuer).\nDo you trust this certificate?", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "No", style: .cancel, handler: CertificateErrorAlert.wrapActionHandler(onDeny)))
        alert.addAction(UIAlertAction(title: "Yes", style: .destructive, handler: CertificateErrorAlert.wrapActionHandler(onAccept)))
        return alert
    }

    fileprivate static func wrapActionHandler(_ action: (() -> Void)?) -> ((UIAlertAction) -> Void)? {
        guard action != nil else {
            return nil
        }
        return { _ in
            action!()
        }
    }
}
