//
//  LoadingSpinnerModel.swift
//  MVMCoreUI
//
//  Created by Kevin Christiano on 5/20/20.
//  Copyright © 2020 Verizon Wireless. All rights reserved.
//

import Foundation
import MVMCore
import VDS

open class LoadingSpinnerModel: MoleculeModelProtocol {
    //--------------------------------------------------
    // MARK: - Properties
    //--------------------------------------------------
    public static var identifier: String = "loadingSpinner"
    public var id: String = UUID().uuidString
    
    public var backgroundColor: Color?
    public var inverted: Bool = false
    public var diameter: CGFloat = 40
    
    //--------------------------------------------------
    // MARK: - Keys
    //--------------------------------------------------
    
    private enum CodingKeys: String, CodingKey {
        case id
        case moleculeName
        case strokeColor
        case diameter
        case inverted
    }

    //--------------------------------------------------
    // MARK: - Initializer
    //--------------------------------------------------

    public init() {}

    //--------------------------------------------------
    // MARK: - Codec
    //--------------------------------------------------
    
    required public init(from decoder: Decoder) throws {
        let typeContainer = try decoder.container(keyedBy: CodingKeys.self)
        
        id = try typeContainer.decodeIfPresent(String.self, forKey: .id) ?? UUID().uuidString
        
        if let diameter = try typeContainer.decodeIfPresent(CGFloat.self, forKey: .diameter) {
            self.diameter = diameter
        }
        
        if let inverted = try typeContainer.decodeIfPresent(Bool.self, forKey: .inverted) {
            self.inverted = inverted
        }
        
        if let strokeColor = try typeContainer.decodeIfPresent(Color.self, forKey: .strokeColor) {
            self.inverted = !strokeColor.uiColor.isDark()
        }
    }

    public func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(id, forKey: .id)
        try container.encode(moleculeName, forKey: .moleculeName)
        try container.encodeIfPresent(diameter, forKey: .diameter)
        try container.encodeIfPresent(inverted, forKey: .inverted)
    }
}

extension LoadingSpinnerModel {
    public var surface: Surface { inverted ? .dark : .light }
}
