//
//  KeyedDecodingContainer+Decode.swift
//  MVM5G
//
//  Created by Matt Bruce on 4/15/22.
//  Copyright © 2022 Kyle. All rights reserved.
//

import Foundation
import MVMCore


public enum KeyedDecodingContainerError: Error {
    case decode(objectType: String, key: String, message: String)
}

extension KeyedDecodingContainerError: LocalizedError, CustomStringConvertible {
    public var description: String {
        switch self {
        case .decode(let objectType, let key, let message):
            return "Decoding Error for object: \(objectType) on coding key: \(key) with error: \(message)"
        }
    }
    
    public var errorDescription: String? {
        return self.description
    }
}

extension KeyedDecodingContainer {
    public func decode<T: Decodable, K: Decodable>(_ type: T.Type,
                                                   forKey key: Self.Key,
                                                   objectType: K.Type) throws -> T {
        do {
            return try self.decode(type, forKey: key)
        } catch {
            throw KeyedDecodingContainerError.decode(objectType: "\(objectType)", key: key.stringValue, message: error.localizedDescription)
        }
    }
}

extension JSONError: LocalizedError, CustomStringConvertible {
    public var description: String {
        switch self {
        case .pathNotFound:
            return "JSON path not found"
        case .data(path: let path):
            return "JSON data in \(path) is corrupt"
        case .other(error: let error):
            return error.localizedDescription
        case .error(message: let message):
            return message
        }
    }

    public var errorDescription: String? {
       return description
    }
}
