package org.sillyjirafe.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

public class ElementsDB {
	String URL = new String();
	String insertSql = "INSERT OR IGNORE INTO creations (title, url, licence, source, type) VALUES (?, ?, ?, ?, ?)";
	Connection connection;
	
	public ElementsDB(String BDstr) throws SQLException
	{
		URL = BDstr;
		connection = DriverManager.getConnection(URL);
	}
	
	public void LinkToDB() throws SQLException
	{
		try (Statement stmt = connection.createStatement()) {
            stmt.execute("""
                CREATE TABLE IF NOT EXISTS creations (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    title TEXT NOT NULL,
                    url TEXT NOT NULL UNIQUE,
                    licence TEXT NOT NULL,
                    source TEXT NOT NULL,
                    type TEXT NOT NULL
                )
            """);
        }
	}
	
	public void AddEllement(String title, String url, String licence, String source, String type) throws SQLException
	{
		try (PreparedStatement ps = connection.prepareStatement(insertSql)) {
			ps.setString(1, title);
			ps.setString(2, url);
			ps.setString(3, licence);
			ps.setString(4, source);
			ps.setString(5, type);
            ps.executeUpdate();
            System.out.printf("%s added \n", title);
        }
	}
	
	
	public void Close() throws SQLException
	{
	    if (connection != null) {
	        connection.close();
	    }
	}
}
