import Foundation

extension StreamState {
    static func reducer(state: inout StreamState, action: StreamAction) {
        switch action {
        case .streamOpened(let attributes):
            state.streamStatus = .opened
            state.streamAttributes = attributes

        case .streamClosed:
            state.streamStatus = .closed
            state.streamAttributes = [:]

        case .featuresListUpdated(let features):
            for feature in features {
                if let exist = state.streamFeatures.first(where: { $0.featureName == feature.featureName }), exist.isProcessed {
                    continue
                }
                state.streamFeatures.append(feature)
            }
            state.streamFeatures = state.streamFeatures.sorted(by: { feature1, feature2 in feature1.priority < feature2.priority })

        case .featureProcessed(let feature):
            state.streamFeatures = state.streamFeatures.filter({ $0.featureName != feature.featureName})
            state.streamFeatures.append(feature)

        default:
            break
        }
    }
}
