//
//  UIImageRenderingMode+Extension.swift
//  MVMCoreUI
//
//  Created by Nadigadda, Sumanth on 24/03/22.
//  Copyright © 2022 Verizon Wireless. All rights reserved.
//

import Foundation
import UIKit

enum RenderingModeError: Error {
    case notAnRenderingMode
}

extension UIImage.RenderingMode: RawRepresentable {
    
    init?(rawValue: String) {
        switch rawValue {
        case "alwaysOriginal":
            self = .alwaysOriginal
        case "alwaysTemplate":
            self = .alwaysTemplate
        case "automatic":
            self = .automatic
        default:
            return nil
        }
    }
    
    var rawValueString: String {
        switch self {
        case .alwaysOriginal:
            return "alwaysOriginal"
        case .alwaysTemplate:
            return "alwaysTemplate"
        case .automatic:
            return "automatic"
        @unknown default:
            return ""
        }
    }
}

extension UIImage.RenderingMode: Codable {
    public init(from decoder: Decoder) throws {
        let typeContainer = try decoder.singleValueContainer()
        let string = try typeContainer.decode(String.self)
        guard let renderingMode = UIImage.RenderingMode(rawValue: string) else {
            throw RenderingModeError.notAnRenderingMode
        }
        self = renderingMode
    }
    
    public func encode(to encoder: Encoder) throws {
        var container = encoder.singleValueContainer()
        try container.encode(rawValueString)
    }
}
