package de.duehl.swing.ui.components.selections.datetime;

/*
 * Copyright 2017 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.FlowLayout;

import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.JSpinner.ListEditor;

import de.duehl.swing.data.MinuteHour;
import de.duehl.swing.ui.components.selections.datetime.spinnermodels.CyclingSpinnerListModel;
import de.duehl.swing.ui.components.selections.datetime.spinnermodels.HourSpinnerModel;

/**
 * Diese Klasse stellt die abstrakte Basis für die Auswahl einer Uhrzeit mit zwei JSpinnern für
 * die Stunden und die  Minuten dar.
 *
 * @version 1.01     2017-03-27
 * @author Christian Dühl
 */

class TimeSelectionBase {

    private final CyclingSpinnerListModel<String> hourSpinnerModel;
    private final CyclingSpinnerListModel<String> minuteSpinnerModel;

    private final JPanel panel;
    private final JSpinner hourSpinner;
    private final JSpinner minuteSpinner;

    public TimeSelectionBase(CyclingSpinnerListModel<String> minuteSpinnerModel) {
        hourSpinnerModel = new HourSpinnerModel();
        this.minuteSpinnerModel = minuteSpinnerModel;

        hourSpinner = new JSpinner(hourSpinnerModel);
        ListEditor hourEditor = new JSpinner.ListEditor(hourSpinner);
        hourSpinner.setEditor(hourEditor);

        minuteSpinner = new JSpinner(minuteSpinnerModel);
        ListEditor minuteEditor = new JSpinner.ListEditor(minuteSpinner);
        minuteSpinner.setEditor(minuteEditor);

        panel = createPanel();
    }

    private JPanel createPanel() {
        JPanel panel = new JPanel();
        panel.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0));

        panel.add(hourSpinner);
        panel.add(new JLabel(":"));
        panel.add(minuteSpinner);

        return panel;
    }

    public final JPanel getPanel() {
        return panel;
    }

    public final MinuteHour getTime() {
        String hour = hourSpinnerModel.getSelectedValue();
        String minute = minuteSpinnerModel.getSelectedValue();
        return new MinuteHour(hour + ":" + minute);
    }

    public final void setTime(MinuteHour time) {
        hourSpinner.setValue(time.getHour());
        minuteSpinner.setValue(time.getMinute());
    }

}
