package eu.eudat.data.converters;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.format.datetime.DateFormatter;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

/**
 * Created by ikalyvas on 9/25/2018.
 */
@Converter
public class DateToUTCConverter implements AttributeConverter<Date, Date> {
    private static final Logger logger = LoggerFactory.getLogger(DateToUTCConverter.class);

    @Override
    public Date convertToDatabaseColumn(Date attribute) {
        if(attribute == null) return null;
        DateFormat formatterIST = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        formatterIST.setTimeZone(TimeZone.getTimeZone("UTC"));
        try {
            String date = formatterIST.format(attribute);
            return formatterIST.parse(date);
        } catch (ParseException e) {
            logger.error(e.getMessage(), e);
        }
        return null;
    }

    @Override
    public Date convertToEntityAttribute(Date dbData) {
        if(dbData == null) return null;
        DateFormat formatterIST = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        formatterIST.setTimeZone(TimeZone.getTimeZone("UTC"));
        try {
            String date = formatterIST.format(dbData);
            return formatterIST.parse(date);
        } catch (ParseException e) {
            logger.error(e.getMessage(), e);
        }
        return null;
    }
}
