package coe318.lab7;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * A circuit made of any number of components, kept in the order they were
 * added.
 *
 * @author rocky
 */
public class Circuit {

    private final ArrayList<Component> components;

    /**
     * Creates an empty circuit.
     */
    public Circuit() {
        components = new ArrayList<>();
    }

    /**
     * Adds a component to the circuit.
     *
     * @param component the component to add
     * @throws IllegalArgumentException if component is null
     */
    public void add(Component component) {
        if (component == null) {
            throw new IllegalArgumentException("Component cannot be null");
        }
        components.add(component);
    }

    /**
     * Returns the number of components in the circuit.
     *
     * @return the number of components
     */
    public int size() {
        return components.size();
    }

    /**
     * Returns the components in the order they were added.
     *
     * @return a read-only list of the components
     */
    public List<Component> getComponents() {
        return Collections.unmodifiableList(components);
    }

    /**
     * Returns the SPICE description of the circuit. Components are listed in
     * the order they were added, and each kind is numbered on its own
     * (V1, R1, V2, R2, R3, ...).
     *
     * @return the SPICE lines separated by newlines, or an empty string if the
     * circuit has no components
     */
    public String toSpice() {
        Map<String, Integer> counts = new HashMap<>();
        StringBuilder sb = new StringBuilder();
        for (Component c : components) {
            String prefix = c.getSpicePrefix();
            int number = counts.getOrDefault(prefix, 0) + 1;
            counts.put(prefix, number);
            if (sb.length() > 0) {
                sb.append('\n');
            }
            sb.append(c.toSpice(number));
        }
        return sb.toString();
    }
}
