/* UtilLib - Copyright (c) 2016-2025 Vincent Calame - Exemole
 * Logiciel libre donné sous triple licence :
 * 1) selon les termes de la CeCILL V2
 * 2) selon les termes de l’EUPL V.1.1
 * 3) selon les termes de la GNU GPLv3
 * Voir le fichier licences.txt
 */


package net.mapeadores.util.date;

import java.time.LocalDate;
import java.time.chrono.IsoChronology;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.format.FormatStyle;
import java.util.Locale;
import net.mapeadores.util.annotation.Nullable;


/**
 *
 * @author Vincent Calame
 */
public final class DateUtils {

    public final static String ISO_JAVAPATTERN = "y-MM-dd";

    private DateUtils() {

    }

    public static String isoNow() {
        return DateTimeFormatter.ISO_LOCAL_DATE.format(LocalDate.now());
    }

    public static int getLastDayOfMonth(int month, int year) {
        switch (month) {
            case 1:
                return 31;
            case 2:
                if (isLeapYear(year)) {
                    return 29;
                } else {
                    return 28;
                }
            case 3:
                return 31;
            case 4:
                return 30;
            case 5:
                return 31;
            case 6:
                return 30;
            case 7:
                return 31;
            case 8:
                return 31;
            case 9:
                return 30;
            case 10:
                return 31;
            case 11:
                return 30;
            case 12:
                return 31;
            default:
                throw new IllegalArgumentException("unknown mois");
        }
    }

    public static boolean isLeapYear(int year) {
        if ((year % 4) != 0) {
            return false;
        }
        if ((year % 400) == 0) {
            return true;
        }
        if ((year % 100) == 0) {
            return false;
        }
        return true;
    }

    public static int compare(@Nullable LocalDate date1, @Nullable LocalDate date2) {
        if (date1 != null) {
            if (date2 == null) {
                return 1;
            } else {
                return date1.compareTo(date2);
            }
        } else if (date2 != null) {
            return -1;
        } else {
            return 0;
        }
    }

    public static LocalDate max(@Nullable LocalDate date1, @Nullable LocalDate date2) {
        int comp = compare(date1, date2);
        if (comp < 0) {
            return date2;
        } else {
            return date1;
        }
    }

    public static String getLocalizedPattern(FormatStyle formatStyle, Locale locale) {
        return DateTimeFormatterBuilder.getLocalizedDateTimePattern(formatStyle, null, IsoChronology.INSTANCE, locale);
    }

}
