package usda.weru.weps.reports.query;

import de.schlichtherle.truezip.file.TFile;
import de.schlichtherle.truezip.file.TFileReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.sql.SQLException;
import java.sql.Types;
import org.apache.log4j.Logger;
import org.openide.util.Exceptions;
import usda.weru.weps.RunFileData;

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

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

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

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

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

    /**
     *
     * @param con
     * @throws SQLException
     */
    public NotesResultSet(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;
        }
        TFile[] files = c_con.getRunFiles();

        for (int i = 0; i < files.length; i++) {
            TFile runDir = files[i];
            TFile notesFile = new TFile(runDir, RunFileData.NotesFileName);

            if (notesFile.exists()) {
                Object[] row = createNewRow(true);
                setRowValue(row, COLUMN_RUNID, i);

                BufferedReader in = null;
                try {
                    in = new BufferedReader(new TFileReader(notesFile));
                    StringBuilder buffer = new StringBuilder();

                    String line;
                    while ((line = in.readLine()) != null) {
                        buffer.append(line);
                        buffer.append("\n");
                    }

                    setRowValue(row, COLUMN_NOTES, buffer.toString());
                } catch (IOException ioe) {
                    LOGGER.error("Error reading notes file: " + notesFile.getAbsolutePath(), ioe);
                    setRowValue(row, COLUMN_NOTES, null);
                } finally {
                    if (in != null) {
                        try {
                            in.close();
                        } catch (IOException e) {
                            LOGGER.error("Error closing notes file: " + notesFile.getAbsolutePath(), e);
                        }
                    }
                }
            }

        }
        c_filled = true;
    }

}
