package org.sillyjirafe.api;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.sillyjirafe.uoapi.element;

public class Search {
	public static List<element> search(Connection conn, Map<String, String> settings) throws SQLException {
	    List<element> results = new ArrayList<>();
	    String sql = """
	            SELECT * FROM creations 
	            WHERE (? = '' OR title LIKE ?)
	            AND (? = '' OR licence = ?)
	            AND (? = '' OR type = ?)
	        """;

	    try (PreparedStatement ps = conn.prepareStatement(sql)) {
	    	ps.setString(1, settings.getOrDefault("q", ""));
	        ps.setString(2, "%" + settings.getOrDefault("q", "") + "%");
	        ps.setString(3, settings.getOrDefault("licence", ""));
	        ps.setString(4, settings.getOrDefault("licence", ""));
	        ps.setString(5, settings.getOrDefault("type", ""));
	        ps.setString(6, settings.getOrDefault("type", ""));
	        ResultSet rs = ps.executeQuery();

	        while (rs.next()) {
	            results.add(new element(
	                rs.getString("title"),
	                rs.getString("url"),
	                rs.getString("licence"),
	                rs.getString("source"),
	                rs.getString("type")
	            ));
	        }
	    }
	    return results;
	}
}
