package com.hubspot.rosetta.jdbi;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.skife.jdbi.v2.ResultSetMapperFactory;
import org.skife.jdbi.v2.StatementContext;
import org.skife.jdbi.v2.tweak.ResultSetMapper;

import com.hubspot.rosetta.RosettaMapper;

public class RosettaMapperFactory implements ResultSetMapperFactory {
  private static final Set<Class<?>> BLACKLIST = new HashSet<Class<?>>(Arrays.asList(
          Byte.class,
          Short.class,
          Integer.class,
          Long.class,
          Float.class,
          Double.class,
          Boolean.class,
          Character.class,
          String.class,
          java.util.Date.class,
          java.sql.Date.class,
          java.sql.Timestamp.class
  ));

  @Override
  public boolean accepts(@SuppressWarnings("rawtypes") Class type, StatementContext ctx) {
    return !(type.isPrimitive() || type.isArray() || type.isAnnotation() || BLACKLIST.contains(type));
  }

  @Override
  @SuppressWarnings({ "rawtypes", "unchecked" })
  public ResultSetMapper mapperFor(Class type, StatementContext ctx) {
    ObjectMapper objectMapper = RosettaObjectMapperOverride.resolve(ctx);
    final RosettaMapper mapper = new RosettaMapper(type, objectMapper, extractTableName(ctx.getRewrittenSql()));

    return new ResultSetMapper() {

      @Override
      public Object map(int index, ResultSet r, StatementContext ctx) throws SQLException {
        return mapper.mapRow(r);
      }
    };
  }

  private String extractTableName(final String sql) {
    String lowerCaseSql = sql.toLowerCase();

    String from = " from ";
    int fromIndex = lowerCaseSql.indexOf(from);
    if (fromIndex < 0) {
      return null;
    }

    String tableString = sql.substring(fromIndex + from.length());
    if (tableString.startsWith("(")) {
      return null;
    }

    int endTableIndex = tableString.indexOf(' ');

    return endTableIndex < 0 ? tableString : tableString.substring(0, endTableIndex);
  }
}

@@ -88,81 +88,8 @@
 ion;
-%0Aimport java.util.Arrays;%0Aimport java.util.HashSet;%0Aimport java.util.Set;
 %0A%0Aim
@@ -138,16 +138,65 @@
 Mapper;%0A
+import org.skife.jdbi.v2.BuiltInArgumentFactory;%0A
 import o
@@ -444,413 +444,8 @@
 ry %7B
-%0A  private static final Set%3CClass%3C?%3E%3E BLACKLIST = new HashSet%3CClass%3C?%3E%3E(Arrays.asList(%0A          Byte.class,%0A          Short.class,%0A          Integer.class,%0A          Long.class,%0A          Float.class,%0A          Double.class,%0A          Boolean.class,%0A          Character.class,%0A          String.class,%0A          java.util.Date.class,%0A          java.sql.Date.class,%0A          java.sql.Timestamp.class%0A  ));
 %0A%0A  
@@ -626,25 +626,39 @@
 %7C%7C B
-LACKLIST.contains
+uiltInArgumentFactory.canAccept
 (typ

Check BuiltInArgumentFactory