package de.renew.propertymanagementgui.gui;

import java.awt.Dimension;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.swing.BoxLayout;
import javax.swing.JComponent;
import javax.swing.JPanel;

import de.renew.propertymanagement.prop.ConfigurableProperty;
import de.renew.propertymanagementgui.reactivecomponents.Component;
import de.renew.propertymanagementgui.reactivecomponents.State;

import static java.util.stream.Collectors.groupingBy;


/**
 * The content of the settings window. Embeds the side navigation and the _page component.
 */
public class ContentComponent extends Component {

    private final Map<String, List<ConfigurableProperty>> _propertiesByPlugins;

    /**
     * Creates a new ContentComponent.
     *
     * @param properties The properties to display.
     */
    public ContentComponent(Map<String, ConfigurableProperty> properties) {
        _propertiesByPlugins =
            properties.values().stream().collect(groupingBy(ConfigurableProperty::getPluginName));
    }

    @Override
    protected JComponent render() {
        JComponent content = new JPanel();
        setLayoutFor(content);

        State<String> activePlugin = useState();

        renderSideNavIn(content, activePlugin);

        renderPageIn(content, activePlugin);
        return content;
    }

    private void setLayoutFor(JComponent content) {
        content.setMaximumSize(new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE));
        content.setLayout(new BoxLayout(content, BoxLayout.X_AXIS));
    }

    private void renderSideNavIn(JComponent parentContainer, State<String> activePlugin) {
        Map<String, Runnable> pluginEntries = _propertiesByPlugins.keySet().stream().collect(
            Collectors.toMap(
                Function.identity(), // Use the set element itself as the key
                element -> () -> activePlugin.setValue(element)// Create a new Runnable as the value
            ));

        Component sideNav = new SideNavComponent(pluginEntries);
        parentContainer.add(sideNav.get());
    }

    private void renderPageIn(JComponent content, State<String> activePlugin) {
        List<ConfigurableProperty> pluginProperties =
            _propertiesByPlugins.get(activePlugin.getValue());

        Component page = new PageComponent(pluginProperties);
        content.add(page.get());
    }
}
