package org.a6v.mecha.db.mysql;

import com.mchange.v2.c3p0.PooledDataSource;
import lc.db.SymbolDictionary;

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

/**
 * A symbol dictionary implementation for MySQL. This dictionary drives off a single table. The dictionary is
 * case-sensitive.
 *
 * @author Alex Leigh
 * @since mk14 mod0 (CRYSTAL)
 */
public class MysqlSymbolDictionary implements SymbolDictionary {
    private final String tableName;
    private final PooledDataSource ds;

    public MysqlSymbolDictionary(PooledDataSource ds, String tableName) throws SQLException {
        this.tableName = tableName;
        this.ds = ds;
    }

    /**
     * Return the id for the given symbol. If the symbol did not previously exist in the dictionary, it will
     * be added.
     */
    public synchronized int read(String symbol) throws SQLException {
        try (Connection con = ds.getConnection()) {
            try (PreparedStatement lookupQuery = con.prepareStatement("SELECT id FROM " + tableName + " WHERE symbol = ?")) {
                lookupQuery.setString(1, symbol);
                try (ResultSet rs = lookupQuery.executeQuery()) {
                    if (rs.next()) {
                        return rs.getInt(1);
                    }
                }
            }

            try (PreparedStatement insertQuery = con.prepareStatement("INSERT INTO " + tableName + " (symbol) VALUES (?)",
                    PreparedStatement.RETURN_GENERATED_KEYS)) {
                insertQuery.setString(1, symbol);
                insertQuery.execute();

                return JdbcUtil.getFirstGeneratedKey(insertQuery);
            }
        }
    }

    @Override
    public void close() {

    }
}
