package de.renew.propertymanagementgui.gui;

import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.util.Map;
import javax.swing.JComponent;
import javax.swing.JPanel;

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


/**
 * The body of the settings window.
 */
public class BodyComponent extends Component {

    private final Map<String, ConfigurableProperty> _properties;

    private final Runnable _savePropertiesGlobalAction;

    private final Runnable _savePropertiesLocalAction;

    private final ActionListener _footerCloseListener;
    private FooterComponent _footer;

    private ContentComponent _content;
    private final Runnable _defaultPropertiesAction;
    private final Runnable _resetPropertiesAction;

    /**
     * Constructor for the Body Component. It takes the properties to display and the actions to save the properties.
     *
     * @param properties                 The properties to display.
     * @param savePropertiesGlobalAction The action to save the properties globally.
     * @param savePropertiesLocalAction  The action to save the properties locally.
     */
    public BodyComponent(
        Map<String, ConfigurableProperty> properties, Runnable savePropertiesGlobalAction,
        Runnable savePropertiesLocalAction, ActionListener footerCloseListener)
    {
        _properties = properties;
        _savePropertiesGlobalAction = savePropertiesGlobalAction;
        _savePropertiesLocalAction = savePropertiesLocalAction;
        _footerCloseListener = footerCloseListener;
        _defaultPropertiesAction = () -> _content.defaultAll();
        _resetPropertiesAction = () -> _content.resetAll();
    }

    @Override
    protected JComponent render() {
        JPanel body = new JPanel();
        body.setLayout(new BorderLayout());

        renderContentIn(body);
        renderFooterIn(body);

        return body;
    }

    private void renderContentIn(JPanel parentContainer) {
        _content = new ContentComponent(_properties);
        parentContainer.add(_content.get(), BorderLayout.CENTER);
    }

    private void renderFooterIn(JPanel parentContainer) {
        _footer = new FooterComponent(
            _savePropertiesGlobalAction, _savePropertiesLocalAction, _footerCloseListener,
            _defaultPropertiesAction, _resetPropertiesAction);
        parentContainer.add(_footer.get(), BorderLayout.PAGE_END);
    }

    public void settingsChanged() {
        _footer.settingsChanged();
        _content.settingsChanged();
    }
}