//
//  FilterOptions.swift
//  mundraubKit
//
//  Created by Oliver Krakora on 30.08.20.
//  Copyright © 2020 Oliver Ian Krakora. All rights reserved.
//

import Foundation

public struct FilterResponse: Codable {
    
    private let keyedOptions: [String: FilterOption]
    
    public let options: [FilterOption]
    
    public init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: UnknownCodingKey.self)
        let tuples: [(String, FilterOption)] = try container.allKeys.map { key in
            let option = try container.decode(FilterOption.self, forKey: key)
            return (key.stringValue, option)
        }
        self.keyedOptions = Dictionary(tuples) { (first, _) in
            first
        }
        self.options = keyedOptions.values.map { $0 }
    }
    
    public func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: UnknownCodingKey.self)
        try keyedOptions.forEach {
            try container.encode($0.value, forKey: UnknownCodingKey(stringValue: $0.key)!)
        }
    }
}
