package ab.issue.utils;

import android.arch.persistence.room.TypeConverter;
import android.support.annotation.Nullable;

import com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode;

import org.joda.time.DateTime;

import java.util.Calendar;

public final class JodaUtils {

    private JodaUtils() {
    }

    public static DateTime create(@Nullable FirebaseVisionBarcode.CalendarDateTime calendarDateTime) {
        if (calendarDateTime == null) {
            return null;
        }
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, calendarDateTime.getYear());
        calendar.set(Calendar.MONTH, calendarDateTime.getMonth() - 1 /* starts with zero */);
        calendar.set(Calendar.DAY_OF_MONTH, calendarDateTime.getDay());
        calendar.set(Calendar.HOUR, calendarDateTime.getHours());
        calendar.set(Calendar.MINUTE, calendarDateTime.getMinutes());
        calendar.set(Calendar.SECOND, calendarDateTime.getSeconds());
        return new DateTime(calendar.getTimeInMillis());
    }

    @TypeConverter
    public static long toLong(@Nullable DateTime dateTime) {
        return dateTime != null ? dateTime.getMillis() : 0L;
    }

    @TypeConverter
    public static DateTime toDateTime(long millis) {
        return new DateTime(millis);
    }
}
