package com.ankurm.dockercompose;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

/**
 * Nothing here is Docker-compose-specific - this is a plain JdbcTemplate
 * repository. The point of this whole demo is that it needs no special
 * code to find the database: a DataSource autoconfigured from the
 * JdbcConnectionDetails that spring-boot-docker-compose registered is
 * exactly the same kind of bean this repository would get in production,
 * pointed at a database declared with ordinary spring.datasource.*
 * properties instead.
 */
@Repository
public class WidgetRepository {

    private final JdbcTemplate jdbcTemplate;

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

    public void createTable() {
        jdbcTemplate.execute("CREATE TABLE IF NOT EXISTS widget (id SERIAL PRIMARY KEY, name VARCHAR(100) NOT NULL)");
    }

    public int insert(String name) {
        jdbcTemplate.update("INSERT INTO widget (name) VALUES (?)", name);
        return jdbcTemplate.queryForObject("SELECT currval(pg_get_serial_sequence('widget','id'))", Integer.class);
    }

    public String nameOf(int id) {
        return jdbcTemplate.queryForObject("SELECT name FROM widget WHERE id = ?", String.class, id);
    }

    public int count() {
        return jdbcTemplate.queryForObject("SELECT count(*) FROM widget", Integer.class);
    }
}
