//
//  WebviewModel.swift
//  MVMCoreUI
//
//  Created by Kruthika KP on 09/03/20.
//  Copyright © 2020 Verizon Wireless. All rights reserved.
//

import Foundation

@objcMembers public class WebViewModel: MoleculeModelProtocol {
    public static var identifier: String = "webview"
    public var moleculeName: String = WebViewModel.identifier
    public var backgroundColor: Color?
    public var url: URL?
    public var htmlString: String?
    public var height: CGFloat?
    public var borderColor: Color?

    public init(htmlString: String) {
        self.htmlString = htmlString
    }
    
    private enum CodingKeys: String, CodingKey{
        case moleculeName
        case backgroundColor
        case url
        case htmlString
        case height
        case borderColor
    }
    
    required public init(from decoder: Decoder) throws {
        let typeContainer = try decoder.container(keyedBy: CodingKeys.self)
        backgroundColor = try typeContainer.decodeIfPresent(Color.self, forKey: .backgroundColor)
        url = try typeContainer.decodeIfPresent(URL.self, forKey: .url)
        htmlString = try typeContainer.decodeIfPresent(String.self, forKey: .htmlString)
        if url == nil, htmlString == nil {
            throw ModelRegistry.Error.decoderErrorModelNotMapped()
        }
        height = try typeContainer.decodeIfPresent(CGFloat.self, forKey: .height)
        borderColor = try typeContainer.decodeIfPresent(Color.self, forKey: .borderColor)
    }
    
    public func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(moleculeName, forKey: .moleculeName)
        try container.encodeIfPresent(backgroundColor, forKey: .backgroundColor)
        try container.encodeIfPresent(url, forKey: .url)
        try container.encodeIfPresent(htmlString, forKey: .htmlString)
        try container.encodeIfPresent(height, forKey: .height)
        try container.encodeIfPresent(borderColor, forKey: .borderColor)
    }
}
