import Foundation
import Network
import WebRTC
import TigaseSwift

extension ExternalServiceDiscoveryModule.Service {
    static let VALID_SERVICE_TYPES = ["stun", "stuns", "turn", "turns"]

    func rtcIceServer() -> RTCIceServer? {
        guard ExternalServiceDiscoveryModule.Service.VALID_SERVICE_TYPES.contains(type) else {
            return nil
        }
        guard !type.hasSuffix("s") || transport == .tcp else {
            return nil
        }
        guard !type.hasPrefix("turn") || username != nil else {
            return nil
        }

        let url = urlString()
        return RTCIceServer(urlStrings: [url], username: username, credential: password, tlsCertPolicy: .insecureNoCheck)
    }

    private func urlString() -> String {
        let host = escapedHost()

        if let port = self.port {
            if let transport = self.transport {
                return "\(type):\(host):\(port)?transport=\(transport.rawValue)"
            } else {
                return "\(type):\(host):\(port)"
            }
        } else {
            if let transport = self.transport {
                return "\(type):\(host)?transport=\(transport.rawValue)"
            } else {
                return "\(type):\(host)"
            }
        }
    }

    private func escapedHost() -> String {
        if #available(iOS 12.0, *) {
            return IPv6Address(self.host) != nil ? "[\(self.host)]" : self.host
        } else {
            return self.host.contains(":") && !(self.host.hasPrefix("[") || self.host.hasSuffix("]")) ? "[\(self.host)]" : self.host
        }
    }
}
