/*
 * Copyright (C) 2025  Tim Zimmermann <tim@aglais.org>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.aglais.zms.ui.component;

import javax.swing.*;
import java.util.Date;

/**
 * A {@link SpinnerDateModel} extension that supports nullable dates.
 * This model allows the spinner to hold a null value in addition to Date values,
 * enabling more flexible date selection and display in UI components.
 */
public class NullableSpinnerDateModel extends SpinnerDateModel {

    private Date date;

    @Override
    public Date getDate() {
        return date;
    }

    @Override
    public Object getValue() {
        return getDate();
    }

    @Override
    public void setValue(Object value) {
        if (value != null) {
            boolean stateChanged = false;
            if (value instanceof Date dateValue) {
                // If the value previously was null, fire a state changed event in case the date has changed
                // since SpinnerDateModel isn't aware of the value being null
                stateChanged = date == null && dateValue.equals(super.getDate());

                date = dateValue;
            }

            super.setValue(value);

            if (stateChanged)
                fireStateChanged();
        } else if (date != null) {
            date = null;

            fireStateChanged();
        }
    }
}