package usda.weru.weps.reports.query;

import de.schlichtherle.truezip.file.TFile;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import org.apache.log4j.Logger;
import org.openide.util.Exceptions;
import usda.weru.mcrew.ManageData;

/**
 *
 * @author joelevin
 */
public class ManagementNotesResultSet extends WepsResultSet {

    private static final Logger LOGGER = Logger.getLogger(ManagementNotesResultSet.class);

    /**
     *
     */
    public static final String NAME = "managementnotes";

    /**
     *
     */
    public static final String COLUMN_RUNID = "runid";

    /**
     *
     */
    public static final String COLUMN_NOTES = "notes";
    private final WepsConnection c_con;
    private boolean c_filled;

    private static final String SQL = "SELECT \"runid\", \"manage\" FROM weps('runs')";

    /**
     *
     * @param con
     * @throws SQLException
     */
    public ManagementNotesResultSet(WepsConnection con) throws SQLException {
        c_con = con;
        addColumn(COLUMN_RUNID, Types.INTEGER, 10, 0);
        addColumn(COLUMN_NOTES, Types.VARCHAR, 5000, 0);
    }

    /**
     *
     * @return
     */
    @Override
    public String getName() {
        return NAME;
    }

    /**
     *
     * @throws SQLException
     */
    @Override
    public synchronized void fill() throws SQLException {

        if (c_filled) {
            return;
        }
        PreparedStatement statement = null;
        try {
            //Query the output resultset so we don't have to read all the same files into memory again
            statement = c_con.prepareStatement(SQL);
            ResultSet rs = statement.executeQuery();

            //loop over all the runs
            while (rs.next()) {
                int runId = rs.getInt(COLUMN_RUNID);
                String managepath = rs.getString(RunsResultSet.COLUMN_MANAGE);

                TFile manageFile = new TFile(managepath);

                if (manageFile.exists()) {
                    ManageData manage = new ManageData();
                    manage.readDataFile(managepath);

                    Object[] row = createNewRow(true);
                    setRowValue(row, COLUMN_RUNID, runId);
                    setRowValue(row, COLUMN_NOTES, manage.getWepsManFileNotes());

                    manage.clear();

                }
            }
            c_filled = true;
        } catch (SQLException e) {
            LOGGER.warn("Error reading managment notes.", e);
        } finally {
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    LOGGER.warn("Unable to close sql statement.", e);
                }
            }
        }
    }

}
