package pl.qumak.xml;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.Date;

@Converter(autoApply = true)
public class ToUTCDateConverter implements AttributeConverter<LocalDateTime, Date> {

    @Override
    public Date convertToDatabaseColumn(LocalDateTime dateTime) {
        if (dateTime == null) return null;
        int offsetSeconds = ZoneOffset.systemDefault().getRules().getOffset(dateTime).getTotalSeconds();
        //odejmij ta roznice od podanego czasu
        LocalDateTime dateAdjustedToCet = dateTime.minusSeconds(offsetSeconds);
        //zrob instant w strefie czasowej
        Instant cetInstant = ZonedDateTime.of(dateAdjustedToCet ,ZoneOffset.systemDefault()).toInstant();
        Date date = Date.from(cetInstant);
        return date;
    }

    @Override
    public LocalDateTime convertToEntityAttribute(Date utcDate) {
        if (utcDate == null) return null;
        Instant instant = utcDate.toInstant();
        // zaloz ze podana data UTC to tak własciwie data w aktualnej strefie czasowej
        LocalDateTime utcLocalDateTime = LocalDateTime.ofInstant(instant,ZoneId.systemDefault());
        // wylicz roznice w pomiedzy aktualna strefa czaswoa a UTC
        int offsetSeconds = ZoneOffset.systemDefault().getRules().getOffset(utcLocalDateTime).getTotalSeconds();
        // dodaj ta roznice
        LocalDateTime localTimezone =  utcLocalDateTime.plusSeconds(offsetSeconds);
        return localTimezone;
    }

}
