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 java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.log4j.Logger;
import org.openide.util.Exceptions;

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

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

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

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

    /**
     *
     */
    public static final String COLUMN_DATE = "date";

    /**
     *
     */
    public static final String COLUMN_OPERATION = "operation";

    /**
     *
     */
    public static final String COLUMN_CROP = "crop";

    private final WepsConnection c_con;
    private boolean c_filled;

    /**
     *
     * @param con
     * @throws SQLException
     */
    public ManagementResultSet(WepsConnection con) throws SQLException {
        c_con = con;
        addColumn(COLUMN_RUNID, Types.INTEGER, 10, 0);
        addColumn(COLUMN_DATE, Types.DATE, 0, 0);
        addColumn(COLUMN_OPERATION, Types.VARCHAR, 255, 0);
        addColumn(COLUMN_CROP, Types.VARCHAR, 255, 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();
        DateFormat harvestDateFormat = new SimpleDateFormat("dd/MM/yyyy");

        for (int runIndex = 0; runIndex < files.length; runIndex++) {
            TFile runDir = files[runIndex];
            TFile manageFile = new TFile(runDir, "mandate.out");

            if (manageFile.exists()) {
                BufferedReader in = null;
                try {
                    in = new BufferedReader(new TFileReader(manageFile));
                    String line = in.readLine();    //first line is uncommented jibberish about number of years
                    while ((line = getLine(in)) != null) {

                        Object[] row = createNewRow(true);
                        setRowValue(row, COLUMN_RUNID, runIndex);

                        String[] parts = line.split("\\|", -1);

                        //date
                        try {
                            String dateString = parts[0].trim();
                            Date harvestDate = harvestDateFormat.parse(dateString);
                            setRowValue(row, COLUMN_DATE, new java.sql.Date(harvestDate.getTime()));
                        } catch (ParseException pe) {
                            LOGGER.error("Error parsing harvest date.", pe);
                        }

                        //operation name
                        try {
                            String operation = parts[1].trim();
                            setRowValue(row, COLUMN_OPERATION, operation);
                        } catch (SQLException e) {
                            LOGGER.error("Error reading crop name.", e);
                        }

                        //crop name
                        try {
                            String crop = parts[2].trim();
                            setRowValue(row, COLUMN_CROP, crop);
                        } catch (SQLException e) {
                            LOGGER.error("Error reading crop name.", e);
                        }
                    }
                } catch (IOException ioe) {
                    LOGGER.error("Error reading mandate file: " + manageFile.getAbsolutePath(), ioe);
                } finally {
                    if (in != null) {
                        try {
                            in.close();
                        } catch (IOException e) {
                            LOGGER.error("Error closing mandate file: " + manageFile.getAbsolutePath(), e);
                        }
                    }
                }
            }

        }

        c_filled = true;
    }

    //Skip comments and blank lines
    private String getLine(BufferedReader in) throws IOException {
        String temp;
        while ((temp = in.readLine()) != null) {
            temp = temp.trim();
            if (temp.length() == 0) {
                //blank line
                continue;
            }
            if (temp.charAt(0) != '#') {
                //not a comment
                return temp;
            }
        }
        return null;
    }

}
