package fr.titionfire.ffsaf.data;

import org.hibernate.boot.model.naming.Identifier;
import org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl;
import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment;

public class SafcaNamingStrategy extends PhysicalNamingStrategyStandardImpl {

    private final static String PREFIX = "ffsaf__";

    @Override
    public Identifier toPhysicalTableName(Identifier name, JdbcEnvironment context) {
        return new Identifier(convertToSnakeCasePrefixed(name.getText()), name.isQuoted());
    }

    @Override
    public Identifier toPhysicalColumnName(Identifier name, JdbcEnvironment context) {
        return new Identifier(convertToSnakeCase(name.getText()), name.isQuoted());
    }

    private String convertToSnakeCase(final String identifier) {
        final String regex = "([a-z])([A-Z])";
        final String replacement = "$1_$2";
        return identifier
                .replaceAll(regex, replacement)
                .toLowerCase();
    }

    private String convertToSnakeCasePrefixed(final String identifier) {
        final String regex = "([a-z])([A-Z])";
        final String replacement = "$1_$2";
        final String newName = identifier
                .replaceAll(regex, replacement)
                .toLowerCase();
        return PREFIX + newName;
    }
}
