package com.pingcap.kb.integration.template;

import com.github.jknack.handlebars.io.AbstractTemplateLoader;
import com.github.jknack.handlebars.io.StringTemplateSource;
import com.github.jknack.handlebars.io.TemplateSource;
import java.io.IOException;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

@Component
public class JdbcTemplateLoader extends AbstractTemplateLoader {

  private final JdbcTemplate jdbcTemplate;

  public JdbcTemplateLoader(JdbcTemplate jdbcTemplate) {
    this.jdbcTemplate = jdbcTemplate;
  }

  @Override
  public TemplateSource sourceAt(String s) throws IOException {
    try {
      String template = jdbcTemplate.queryForObject("SELECT content FROM templates WHERE name = ?", String.class, s);
      if (template == null) {
        return null;
      }
      return new StringTemplateSource(s, template);
    } catch (EmptyResultDataAccessException ignore) {
      return null;
    }catch (DataAccessException dae) {
      throw new IOException(dae);
    }
  }
}
