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

/*
 * 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.Dimension;

import javax.swing.JFrame;
import javax.swing.SwingUtilities;

import de.duehl.swing.logic.Quitter;
import de.duehl.swing.ui.GuiTools;
import de.duehl.swing.ui.layout.card.CardHandling;
import de.duehl.swing.ui.layout.card.CardSwitcher;
import de.duehl.swing.ui.listener.ClosingWindowListener;

public class CardLayoutDemo implements CardSwitcher, Quitter {

    private final JFrame frame;
    private final CardHandling cardHandling;

    public CardLayoutDemo() {
        frame = new JFrame();
        cardHandling = new CardHandling(new DemoCards());

        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                createGui();
            }
        });
    }

    private void createGui() {
        frame.setTitle("CardLayoutDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.addWindowListener(new ClosingWindowListener(this));
        frame.setLayout(new BorderLayout());

        frame.add(createCardPanel(), BorderLayout.CENTER);

        frame.setLocation(250, 100);
        frame.setPreferredSize(new Dimension(300, 100));
        frame.pack();
    }

    private Component createCardPanel() {
        cardHandling.addAllCardsToPanel((CardSwitcher) this);
        return cardHandling.getCardPanel();
    }

    @Override
    public void switchCard() {
        cardHandling.switchCard();
    }

    @Override
    public void close() {
        frame.setVisible(false);
        frame.dispose();
    }

    public void start() {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                frame.setVisible(true);
            }
        });
    }

    @Override
    public void quit() {
        boolean quit = GuiTools.askUserToQuit(frame);
        if (quit) {
            cardHandling.quit();
            close();
        }
    }

    public static void main(String[] args) {
        new CardLayoutDemo().start();
    }

}
