//
//  UnOrderedListModel.swift
//  MVMCoreUI
//
//  Created by Murugan, Vimal on 10/01/20.
//  Copyright © 2020 Verizon Wireless. All rights reserved.
//

import Foundation

@objcMembers public class UnOrderedListModel: StackModel {
    public override class var identifier: String {
        return "unOrderedList"
    }
    public var bulletChar = "•"
    public var bulletColor: Color
    
    private enum CodingKeys: String, CodingKey {
        case moleculeName
        case backgroundColor
        case list
        case bulletChar
        case bulletColor
    }

    // Numbered list model comes in the from of list = [MoleculeModelProtocol]
    public required init(from decoder: Decoder) throws {
        let typeContainer = try decoder.container(keyedBy: CodingKeys.self)
        if let bulletChar = try typeContainer.decodeIfPresent(String.self, forKey: .bulletChar) {
            self.bulletChar = bulletChar
        }

        bulletColor = try typeContainer.decodeIfPresent(Color.self, forKey: .bulletColor) ?? Color(uiColor: .mvmBlack)
        let list: [MoleculeModelProtocol] = try typeContainer.decodeModels(codingKey: .list)
        var models: [MoleculeStackItemModel] = []
        for molecule in list {
            models.append(MoleculeStackItemModel(with: StringAndMoleculeModel(string: bulletChar, molecule: molecule, stringColor: bulletColor)))
        }
        super.init(molecules: models, spacing: Padding.Four)
    }
    
    public override func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(bulletChar, forKey: .bulletChar)
        try container.encodeIfPresent(backgroundColor, forKey: .backgroundColor)
        try container.encode(moleculeName, forKey: .moleculeName)
        
        var models: [MoleculeModelProtocol] = []
        for molecule in molecules {
            models.append(((molecule as! MoleculeStackItemModel).molecule as! StringAndMoleculeModel).molecule)
        }
        try container.encodeModels(models, forKey: .list)
        try container.encode(bulletColor, forKey: .bulletColor)
    }
}
