package com.atlassian.stash.internal.jpa;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.persistence.AttributeConverter;
import java.time.DateTimeException;
import java.time.ZoneId;

/**
 * Mapper that converts a {@link ZoneId} to and from a String that can be stored in the database.
 *
 * @since 4.6
 */
public class ZoneIdConverter implements AttributeConverter<ZoneId, String> {

    private static final Logger log = LoggerFactory.getLogger(ZoneIdConverter.class);

    @Override
    public String convertToDatabaseColumn(ZoneId attribute) {
        return attribute == null ? null : attribute.getId();
    }

    @Override
    public ZoneId convertToEntityAttribute(String dbData) {
        if (dbData == null) {
            return null;
        }
        try {
            return ZoneId.of(dbData);
        } catch (DateTimeException e) {
            log.debug("Unable to convert '{}' into a valid timezone. Defaulting to null.", dbData);
            return null;
        }
    }
}
