package de.thpeetz.kontor.common.views;

import com.vaadin.flow.component.Unit;
import com.vaadin.flow.component.customfield.CustomField;
import com.vaadin.flow.component.select.Select;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDate;
import java.time.Month;
import java.time.YearMonth;
import java.time.ZoneId;
import java.time.format.TextStyle;
import java.util.List;
import java.util.Locale;
import java.util.stream.IntStream;

@Slf4j
public class YearMonthField extends CustomField<YearMonth> {

    private final Select<Integer> year = new Select<>();;
    private final Select<Month> month = new Select<>();

    public YearMonthField() {
        LocalDate now = LocalDate.now(ZoneId.systemDefault());
        List<Integer> selectableYears = IntStream.range(1970, now.getYear()).boxed().toList();
        year.setItems(selectableYears);
        year.setWidth(6, Unit.EM);
        month.setItems(Month.values());
        month.setItemLabelGenerator(m -> m.getDisplayName(TextStyle.FULL, Locale.getDefault()));
        month.setWidth(9, Unit.EM);
        add(year, month);
    }

    @Override
    protected YearMonth generateModelValue() {
        if (year.getValue() != null && month.getValue() != null) {
            int yearValue = year.getValue();
            int monthValue = month.getValue().getValue();
            YearMonth result = YearMonth.of(yearValue, monthValue);
            log.debug("YearMonthField.generateModelValue() = {}", result);
            return result;
        } else {
            log.debug("YearMonthField.generateModelValue() = null");
            return null;
        }
    }

    @Override
    protected void setPresentationValue(YearMonth yearMonth) {
        if (yearMonth == null) return;
        year.setValue(yearMonth.getYear());
        month.setValue(yearMonth.getMonth());
    }
}
