package leigh.example.calcite.adapter;

import com.google.common.collect.ImmutableMap;
import leigh.mecha.log.MechaLogger;
import leigh.mecha.log.MechaLoggerFactory;
import org.apache.calcite.adapter.java.JavaTypeFactory;
import org.apache.calcite.rel.type.RelDataTypeFactory;
import org.apache.calcite.rel.type.RelDataTypeImpl;
import org.apache.calcite.schema.Table;
import org.apache.calcite.schema.impl.AbstractSchema;
import org.apache.calcite.sql.type.SqlTypeName;
import org.apache.calcite.sql2rel.InitializerExpressionFactory;
import org.apache.calcite.sql2rel.NullInitializerExpressionFactory;

import java.util.Map;

public class ExampleSchema extends AbstractSchema {
    private static final MechaLogger logger = MechaLoggerFactory.getLogger(ExampleSchema.class);
    private final JavaTypeFactory typeFactory;
    private Map<String, Table> tableMap;

    public ExampleSchema(JavaTypeFactory typeFactory) {
        this.typeFactory = typeFactory;
    }

    @Override
    protected Map<String, Table> getTableMap() {
        if (tableMap == null) {
            tableMap = createTableMap();
        }
        return tableMap;
    }

    private Map<String, Table> createTableMap() {
        final ImmutableMap.Builder<String, Table> builder = ImmutableMap.builder();

        builder.put("clock", new ExampleTable());

        final InitializerExpressionFactory ief =
                new NullInitializerExpressionFactory() {

                };

        final RelDataTypeFactory.Builder boxBuilder = typeFactory.builder();
        final RelDataTypeFactory.Builder boxStoredBuilder = typeFactory.builder();

        boxBuilder.add("msg", SqlTypeName.VARCHAR);

        builder.put("box", new ExampleModTable("box", RelDataTypeImpl.proto(boxBuilder.build()),
                RelDataTypeImpl.proto(boxBuilder.build()),
                ief));
        return builder.build();
    }
}
