package leigh.astro.db;

import leigh.astro.catalog.CatalogObject;
import leigh.astro.fits.Exposure;
import leigh.astro.scheduler.Tasking;
import leigh.astro.unit.SphericalCoordinate;

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

/**
 * This class provides access to a remote Astro schema store. This particular implementation supports MySQL.
 *
 * @author Alex Leigh
 */
public class AstroStore {
    private final Connection con;

    public AstroStore(Connection con) {
        this.con = con;
    }

    /**
     * Return a list of taskings to the caller. The taskings are the goals, so they have not had the actuals
     * subtracted.
     */
    public List<Tasking> getTaskings() throws SQLException {
        ArrayList<Tasking> tasks = new ArrayList<>();

        try (PreparedStatement ps = con.prepareStatement(
                "SELECT a.id, a.nm, a.ra_deg, a.dec_deg, b.nm\n" +
                        "FROM ast_catalog_t a,\n" +
                        "     ast_catalog_type_t b\n" +
                        "WHERE a.catalog_type_id = b.id\n" +
                        "  AND (catalog_type_id = 13 OR catalog_type_id = 12)\n" +
                        "  AND a.nm LIKE 'NGC%'")) {
            try (ResultSet rs = ps.executeQuery()) {
                while (rs.next()) {
                    int id = rs.getInt(1);
                    String nm = rs.getString(2);
                    double ra = rs.getDouble(3);
                    double dec = rs.getDouble(4);
                    String type = rs.getString(5);

                    CatalogObject obj = new CatalogObject(nm, new SphericalCoordinate(ra, dec), type, id);
                    Tasking t = new Tasking(obj, Instant.now());
                    t.putTasking(new Exposure(240, 200, 10, Exposure.KEY_HA), 200);
                    t.putTasking(new Exposure(240, 200, 10, Exposure.KEY_OIII), 200);
                    t.putTasking(new Exposure(240, 200, 10, Exposure.KEY_SII), 200);
                    tasks.add(t);
                }
            }
        }

        return tasks;
    }

}
