package de.duehl.swing.ui.start.card.c.output;

/*
 * Copyright 2016 Christian Dühl. All rights reserved.
 *
 * This program is free software. You can redistribute it and/or
 * modify it under the same terms as perl:
 *
 * general:  http://dev.perl.org/licenses/
 * GPL:      http://dev.perl.org/licenses/gpl1.html
 * artistic: http://dev.perl.org/licenses/artistic.html
 */

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;

import de.duehl.swing.ui.layout.card.CardGui;
import de.duehl.swing.ui.layout.card.CardLogic;
import de.duehl.swing.ui.layout.card.CardSwitcher;

public class OutputCardGui implements CardGui {

    private CardSwitcher switcher;
    private JLabel resultLabel;

    @Override
    public void setLogic(CardLogic logic) {
        if (logic instanceof OutputCardLogic) {
            // Diese Gui braucht keinen Zugriff auf die Logik.
            //this.logic = (OutputCardLogic) logic;
        }
        else {
            throw new RuntimeException("Aufruf mit der falschen Logik!");
        }
    }

    @Override
    public Component createGui(CardSwitcher switcher) {
        this.switcher = switcher;

        JPanel panel = new JPanel();
        panel.setLayout(new BorderLayout());

        panel.add(createResultPanel(), BorderLayout.CENTER);
        panel.add(createButtonPanel(), BorderLayout.SOUTH);

        return panel;
    }

    private Component createResultPanel() {
        JPanel panel = new JPanel();
        panel.setLayout(new BorderLayout());

        panel.add(createResultLabel(), BorderLayout.CENTER);

        return panel;
    }

    private Component createResultLabel() {
        resultLabel = new JLabel("");
        resultLabel.setHorizontalAlignment(JLabel.CENTER);
        return resultLabel;
    }

    private Component createButtonPanel() {
        JPanel panel = new JPanel();
        panel.setLayout(new BorderLayout());

        panel.add(createOkButton(), BorderLayout.EAST);

        return panel;
    }

    private Component createOkButton() {
        JButton button = new JButton("Beenden");

        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                apply();
            }
        });

        return button;
    }

    private void apply() {
        switcher.close();
    }

    public void showEven() {
        resultLabel.setText("Die Zahl ist gerade.");
    }

    public void showOdd() {
        resultLabel.setText("Die Zahl ist ungerade.");
    }

    @Override
    public void cleanUp() {
        // Hier muss nichts aufgeräumt werden...
    }

}
