package de.sebse.fuplanner.tools;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import androidx.annotation.Nullable;
import android.text.format.DateFormat;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class UtilsDate {
    @Deprecated
    public static String getModifiedDateTime(long modified) {
        return getModifiedDateTime(null, modified);
    }

    public static String getModifiedDateTime(Context context, long modified) {
        return getModifiedDate(context, modified, "dd.MM.yy hh:mm");
    }

    @Deprecated
    public static String getModifiedTime(long modified) {
        return getModifiedTime(null, modified);
    }

    public static String getModifiedTime(Context context, long modified) {
        return getModifiedDate(context, modified, "hh:mm");
    }

    public static String getModifiedDate(long modified) {
        return getModifiedDate(null, modified, "dd.MM.yy");
    }



    public static String getModifiedDate(@Nullable Context context, long modified, String skeleton) {
        return getModifiedDate(context, Locale.getDefault(), modified, skeleton);
    }

    @SuppressLint("SimpleDateFormat")
    private static String getModifiedDate(@Nullable Context context, Locale locale, long modified, String skeleton) {
        SimpleDateFormat dateFormat;

        if (context != null && DateFormat.is24HourFormat(context))
            skeleton = skeleton.replaceAll("h", "H");
        if (context != null && !DateFormat.is24HourFormat(context))
            skeleton = skeleton.replaceAll("H", "h");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            dateFormat = new SimpleDateFormat(getDateFormat(locale, skeleton));
        } else {
            dateFormat = new SimpleDateFormat(skeleton, locale);
        }

        return dateFormat.format(new Date(modified));
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
    private static String getDateFormat(Locale locale, String skeleton) {
        return DateFormat.getBestDateTimePattern(locale, skeleton);
    }

    public static boolean dateEquals(long a, long b) {
        return a / 86400000 == b / 86400000;
    }

    public static long stringToMillis(String dateString, String format) {
        try {
            @SuppressLint("SimpleDateFormat") SimpleDateFormat sdf = new SimpleDateFormat(format);
            Date date = sdf.parse(dateString);

            return date.getTime();

        } catch (ParseException e) {
            e.printStackTrace();
            return 0;
        }
    }
}
