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

import Foundation

@objcMembers public class NumberedListModel: StackModel {
    public override class var identifier: String {
        return "numberedList"
    }
    public var numberColor: Color
    
    private enum CodingKeys: String, CodingKey {
        case moleculeName
        case backgroundColor
        case list
        case numberColor
    }

    // 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)
        
        numberColor = try typeContainer.decodeIfPresent(Color.self, forKey: .numberColor) ?? Color(uiColor: .mvmBlack)
        let list: [MoleculeModelProtocol] = try typeContainer.decodeModels(codingKey: .list)
        var models: [MoleculeStackItemModel] = []
        for (index, molecule) in list.enumerated() {
            models.append(MoleculeStackItemModel(with: StringAndMoleculeModel(string: "\(index+1).", molecule: molecule, stringColor: numberColor)))
        }
        super.init(molecules: models, spacing: 0)
    }
    
    public override func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        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(numberColor, forKey: .numberColor)
    }
}


