package usda.weru.nrmv;

import java.io.File;
import org.openide.util.Exceptions;
import usda.weru.weps.gui.NrmvProgress;

/**
 *
 * @author Benjamin.Todd
 */
public class ConvertAllToNrmv implements Runnable {

    private final String newDir, runDir;
    boolean shouldDoAverages = true;
    private int progressCounter;
    private NrmvProgress progress;

    // measures how many of the possible input files exist, so the program knows
    // how many to wait for
    private int numberOfFiles;

    private boolean allThreadsStarted;

    public ConvertAllToNrmv(String n, String r) {
        newDir = n;
        runDir = r;
        progress = null;
    }

    @Override
    public void run() {
        /*
         NrmvSummaryOutPut nsop = new NrmvSummaryOutPut();
         nsop.setCaller(this);
         nsop.setLocation(400, 400);

         nsop.setVisible(true);
         nsop.setResizable(true);
         nsop.pack();
         while (!nsop.getIfSelected()) {
         }
         nsop.dispose();
         */
        //System.out.println("Beginning NRMV file creation");
        
        progress = new NrmvProgress();
        progressCounter = 0;

        // this should equal the number of files, and the number of calls to ConvertFile
        progress.getBar().setMaximum(10);
        progress.getBar().setValue(0);
        progress.setLocation(100, 100);
        progress.setVisible(true);

        String nrmvFileLocation = "nrmvfiles";
        String dirPath = runDir + "\\" + nrmvFileLocation;
        java.io.File dir = new java.io.File(dirPath);
        if (!dir.exists()) {
            if (dir.mkdirs()) {
                //System.out.println("Directory (" + dirPath + ") created");
            } else {
                System.out.println("Failed to create directory (" + dirPath + ")");
            }
        }
        nrmvFileLocation = dirPath;

        numberOfFiles = 0;
        allThreadsStarted = false;
        ConvertFile("hydro.out", "hydro", new ConvertHydro(), nrmvFileLocation);
        ConvertFile("decomp.out", "decomp", new ConvertDecomp(), nrmvFileLocation);
        ConvertFile("dabove.out", "dabove", new ConvertAbove(), nrmvFileLocation);
        ConvertFile("crop.out", "crop", new ConvertCrop(), nrmvFileLocation);
        ConvertFile("hlayers.out", "hlayers", new ConvertLayers(), nrmvFileLocation);
        ConvertFile("plot.out", "plot", new ConvertPlot(), nrmvFileLocation);
        ConvertFile("season.out", "season", new ConvertSeason(), nrmvFileLocation);
        ConvertFile("shoot.out", "shoot", new ConvertShoot(), nrmvFileLocation);
        ConvertFile("dbelow.out", "dbelow", new ConvertBelow(), nrmvFileLocation);
        ConvertFile("soillay.out", "soillay", new ConvertSoilLayer(), nrmvFileLocation);
        allThreadsStarted = true;

        // wait for all threads to finish. timeout of forty seconds
        synchronized (this) {
            try {
                this.wait(40000);
            } catch (InterruptedException ex) {
                Exceptions.printStackTrace(ex);
            }
        }
        // check that the condition is actually met, and we didn't just time out
        if (numberOfFiles > progressCounter) {
            System.out.println("Timeout. Not all files could be read.");
        }

        try {
            progress.setStatus("Finished");
            // sleep for 2 seconds to let the user see that it is finished
            Thread.sleep(2000);
            progress.setVisible(false);
            progress.dispose();
            //System.out.println("converted successfully");
        } catch (InterruptedException ex) {
            Exceptions.printStackTrace(ex);
        }

    }

    private void ConvertFile(String filename, String name, NrmvConverter nc, String nrmvFileLocation) {
        File file = new File(runDir + "\\" + filename);
        if (file.exists()) {
            numberOfFiles++;
            try {
                NrmvThread nv = new NrmvThread(nc, shouldDoAverages, newDir, runDir, filename, nrmvFileLocation, name, this);
                nv.initialize();
            } catch (Exception e) {
                progress.setError(name + " " + e.toString());
            }
        } else {
            System.out.println("File does not exist : " + runDir + "\\" + filename);
        }
    }

    public void setProgressBarError(String str) {
        this.progress.setError(str);
    }

    public void shouldDoAverages(boolean b) {
        shouldDoAverages = b;
    }

    public synchronized void increaseCounter() throws InterruptedException {
        progressCounter++;
        progress.setStatus("Converting");
        progress.getBar().setValue(progressCounter);
        // notifies the main thread when all of the conversion threads are done
        if (allThreadsStarted && progressCounter == numberOfFiles) {
            synchronized (this) {
                this.notify();
            }
        }
    }
}
