package liquibase.ext;

import liquibase.database.Database;
import liquibase.database.structure.type.BlobType;
import liquibase.database.typeconversion.core.PostgresTypeConverter;

import java.sql.Types;
import java.text.ParseException;

@SuppressWarnings("unused")
public class CustomPostgresTypeConverter extends PostgresTypeConverter {
    @Override
    public int getPriority() {
        return Priority.PRIORITY_OVERRIDE;
    }

    @Override
    public BlobType getBlobType() {
        return new BlobType("oid");
    }

    @Override
    public Object convertDatabaseValueToObject(Object defaultValue, int databaseDataType, int firstParameter, int secondParameter, Database database) throws ParseException {
        if (defaultValue instanceof String) {
            defaultValue = ((String) defaultValue).replaceAll("'::[\\w\\s]+$", "'");

            if (databaseDataType == Types.TIMESTAMP) {
                //remove trailing time zone info
                defaultValue = ((String) defaultValue).replaceFirst("[\\+-]\\d+$", "");
            }
            return convertToCorrectObjectType(((String) defaultValue).replaceFirst("^'", "").replaceFirst("'$", ""), databaseDataType, firstParameter, secondParameter, database);
        } else {
            return defaultValue;
        }
    }

}
