package com.bonus.canteen.core.config.json;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@MappedTypes({JsonNode.class})
public class JsonNodeTypeHandler extends BaseTypeHandler<JsonNode> {
   private static final Logger log = LoggerFactory.getLogger(JsonNodeTypeHandler.class);
   private final ObjectMapper objectMapper = new ObjectMapper();

   public void setNonNullParameter(PreparedStatement preparedStatement, int i, JsonNode jsonNode, JdbcType jdbcType) throws SQLException {
      preparedStatement.setString(i, jsonNode.toString());
   }

   private JsonNode read(String json) {
      if (json != null && !json.isEmpty()) {
         try {
            return this.objectMapper.readTree(json);
         } catch (JsonProcessingException var3) {
            log.warn("JSON parse failed", var3);
            return null;
         }
      } else {
         return null;
      }
   }

   public JsonNode getNullableResult(ResultSet rs, String columnName) throws SQLException {
      String json = rs.getString(columnName);
      return this.read(json);
   }

   public JsonNode getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
      String json = rs.getString(columnIndex);
      return this.read(json);
   }

   public JsonNode getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
      String json = cs.getString(columnIndex);
      return this.read(json);
   }
}
