//
//  AccordionListItemModel.swift
//  MVMCoreUI
//
//  Created by Scott Pfeil on 1/13/20.
//  Copyright © 2020 Verizon Wireless. All rights reserved.
//

import UIKit

class AccordionListItemModel: MoleculeListItemModel {
    //--------------------------------------------------
    // MARK: - Properties
    //--------------------------------------------------
    
    override public class var identifier: String { "accordionListItem" }
    
    public var molecules: [ListItemModelProtocol & MoleculeModelProtocol]
    public var hideLineWhenExpanded: Bool = false
    public var selected: Bool = false
    
    private var added: Bool = false

    //--------------------------------------------------
    // MARK: - Keys
    //--------------------------------------------------
    
    private enum CodingKeys: String, CodingKey {
        case moleculeName
        case molecules
        case molecule
        case hideLineWhenExpanded
        case selected
    }
    
    //--------------------------------------------------
    // MARK: - Methods
    //--------------------------------------------------
    
    public override func setDefaults() {
        super.setDefaults()
        hideArrow = true
    }
    
    //--------------------------------------------------
    // MARK: - Codec
    //--------------------------------------------------
    
    required public init(from decoder: Decoder) throws {
        let typeContainer = try decoder.container(keyedBy: CodingKeys.self)
        molecules = try typeContainer.decodeModels(codingKey: .molecules)
        selected = try typeContainer.decodeIfPresent(Bool.self, forKey: .selected) ?? false
        if let hideLine = try typeContainer.decodeIfPresent(Bool.self, forKey: .hideLineWhenExpanded) {
            hideLineWhenExpanded = hideLine
        }
        try super.init(from: decoder)
    }
    
    public override func encode(to encoder: Encoder) throws {
        try super.encode(to: encoder)
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(moleculeName, forKey: .moleculeName)
        try container.encodeModels(molecules, forKey: .molecules)
        try container.encode(selected, forKey: .selected)
        try container.encodeIfPresent(hideLineWhenExpanded, forKey: .hideLineWhenExpanded)
    }
}

extension AccordionListItemModel: PageBehaviorProtocolRequirer {
    public func getRequiredBehaviors() -> [PageBehaviorModelProtocol] {
        return [AddRemoveMoleculesBehaviorModel()]
    }
}

extension AccordionListItemModel: AddMolecules {
    public func moleculesToAdd() -> AddMolecules.AddParameters? {
        guard !added, selected else { return nil }
        added = true
        return (molecules, .below)
    }
}

extension AccordionListItemModel: RemoveMolecules {
    public func moleculesToRemove() -> [ListItemModelProtocol & MoleculeModelProtocol]? {
        guard added else { return nil }
        added = false
        return molecules
    }
}
