// Copyright (c) ZeroC, Inc.

import Foundation

/// Determines how the Ice runtime sorts proxy endpoints when establishing a connection.
public enum EndpointSelectionType: UInt8 {
    /// The Ice runtime shuffles the endpoints in a random order.
    case Random = 0

    /// The Ice runtime uses the endpoints in the order they appear in the proxy.
    case Ordered = 1

    public init() {
        self = .Random
    }
}

/// An `Ice.InputStream` extension to read `EndpointSelectionType` enumerated values from the stream.
extension InputStream {
    /// Read an enumerated value.
    ///
    /// - Returns: The enumerated value.
    public func read() throws -> EndpointSelectionType {
        let rawValue: UInt8 = try read(enumMaxValue: 1)
        guard let val = EndpointSelectionType(rawValue: rawValue) else {
            throw MarshalException("invalid enum value")
        }
        return val
    }

    /// Read an optional enumerated value from the stream.
    ///
    /// - Parameter tag: The numeric tag associated with the value.
    /// - Returns: The enumerated value.
    public func read(tag: Int32) throws -> EndpointSelectionType? {
        guard try readOptional(tag: tag, expectedFormat: .Size) else {
            return nil
        }
        return try read() as EndpointSelectionType
    }
}

/// An `Ice.OutputStream` extension to write `EndpointSelectionType` enumerated values to the stream.
extension OutputStream {
    /// Writes an enumerated value to the stream.
    ///
    /// - Parameter value: The enumerator to write.
    public func write(_ value: EndpointSelectionType) {
        write(enum: value.rawValue, maxValue: 1)
    }

    /// Writes an optional enumerated value to the stream.
    ///
    /// - Parameters:
    ///   - tag: The numeric tag associated with the value.
    ///   - value: The enumerator to write.
    public func write(tag: Int32, value: EndpointSelectionType?) {
        guard let v = value else {
            return
        }
        write(tag: tag, val: v.rawValue, maxValue: 1)
    }
}
