package usda.weru.mcrew;

//
//Title:        WEPS XML Management File Updater
//Version:
//Author:       Jim Frankenberger
//Company:      USDA-ARS
//Date:         June 23, 2003
//Description:  Updates WEPS XML management files with the latest crop and operation database records. Also allows names to
//              be fixed with the correct subdirectories for crops and operations.
//
import de.schlichtherle.truezip.file.TFile;
import java.awt.Component;
import java.awt.Frame;
import java.io.FileFilter;

import java.io.FilenameFilter;
import java.io.IOException;
import java.util.List;
import java.util.Stack;
import java.util.Vector;
import javax.swing.JOptionPane;

import org.apache.log4j.Logger;
import org.openide.util.Exceptions;
import usda.weru.util.WepsFileTypes;

class XMLManagementUpdater implements Runnable {

    StatusDialog statDialog;
    int finalCount = 0;
    List<String> tempDb = new Vector<String>();
    Thread mainUpdateThread;
    Component parent;//Reference to the parent window-MCREW
    private static int THREAD_COUNTER;

    //
    // XMLFileFilter
    //
    // Generic class to implement a FilenameFilter to return all files with a specific extension and also
    // to walk down into directories.
    //
    private static class XMLFileFilter implements FilenameFilter {

        String theFilter;

        XMLFileFilter(String filter) {
            theFilter = filter;
        }

        //Accept all directories and all MAN files.
        @Override
        public boolean accept(java.io.File dir, String name) {
            TFile f = new TFile(dir, name);
            if (f.isDirectory()) {
                return true;
            }
            if (name.endsWith("." + theFilter)) {
                return true;
            }
            return false;
//        String fullname="";
//         try {
//            fullname = dir.getCanonicalPath() + "/" + name;
//         } catch (Exception e) {
//                
//         }
//        
//        File f = new File(fullname);
//        if (f.isDirectory()) {
//            return true;
//        }
//      
//        String ext = null;
//        String s = name;
//        int i = s.lastIndexOf('.');
//
//        if (i > 0 &&  i < s.length() - 1) {
//            ext = s.substring(i+1).toLowerCase();
//        }
//        String extension = ext;
//        if (extension != null) {
//            if (extension.equals(theFilter)) {
//               return true;
//            } else {
//                return false;
//            }
//        }
//
//        return false;
//
        }
    }

    /**
     * This function just takes the directory , performs recursion, searches for the 
     * desired files, puts them in a vector and returns them.
     */
    public Vector<String> onlyRecursion(String dir, String filterName) {
        Vector<String> dirVector = new Vector<String>();
        //XMLFileFilter filter = new XMLFileFilter("man");
        XMLFileFilter filter = new XMLFileFilter(filterName);
        TFile currentDir = new TFile(dir);

        if (currentDir.isDirectory() == false) {
            JOptionPane.showMessageDialog(null, "Directory is not valid: " + dir, "Error", JOptionPane.INFORMATION_MESSAGE);
            return null;
        }


        /*
         // test it skel directory exists to hold temp files
         File fs = new File(ConfigData.getDirectoryName(XMLConstants.smanagement_skeleton));
         if ((!fs.exists()) || (!fs.isDirectory())) {
         JOptionPane.showMessageDialog(null,"Skeleton directory is not valid: \n\n"+
         ConfigData.getDirectoryName(XMLConstants.smanagement_skeleton),
         "Error",JOptionPane.INFORMATION_MESSAGE);
         return null;    
         }
         */
        Stack<TFile> alldirs = new Stack<TFile>();
        alldirs.push(currentDir);

        // Build a list of the files to process.
        while (alldirs.empty() == false) {
            currentDir = alldirs.pop();

            for (java.io.File f : currentDir.listFiles(filter)) {
                try {
                    String dname = f.getCanonicalPath();
                    if (!f.isDirectory()) {
                        dirVector.addElement(dname);
                    } else {
                        dirVector.addElement(dname);
                        alldirs.push(new TFile(f));
                    } //end of if-else
                } catch (IOException ex) {
                    Logger.getLogger(XMLManagementUpdater.class).error(ex);
                }
            }//end of for loop
        }//end of while
        return dirVector;
    }//end of onlyRecursion
    
    Vector<String> db = new Vector<>();
    
    /* The method updateDirectory() is called to update all the .man files 
     * in a specific directory, if the recurse flag is set then all management files
     * in any subdirectories are also updated.
     */
    public void updateDirectory(Component parent, String dir, boolean recurse) {
        int count = 0;
        this.parent = parent;
        count = doRecursion(dir, recurse);
        if (count != 0) {
            doUpdate(parent, db);
        }

    }//end of method  updateDirectory   

    public int doRecursion(String dir, boolean recurse) {

        //XMLFileFilter filter = new XMLFileFilter("man");        
        TFile currentDir = new TFile(dir);

        if (currentDir.isDirectory() == false) {
            JOptionPane.showMessageDialog(null, "Directory is not valid: " + dir, "Error", JOptionPane.INFORMATION_MESSAGE);
            return 0;
        }

        // test it skel directory exists to hold temp files
        TFile fs = new TFile(MCREWConfig.getDirectoryName(XMLConstants.smanagement_skeleton));
        if ((!fs.exists()) || (!fs.isDirectory())) {
            JOptionPane.showMessageDialog(null, "Skeleton directory is not valid: \n\n"
                    + MCREWConfig.getDirectoryName(XMLConstants.smanagement_skeleton),
                    "Error", JOptionPane.INFORMATION_MESSAGE);
            return 0;
        }
        Stack<TFile> alldirs = new Stack<>();
        alldirs.push(currentDir);

        FileFilter filter = new FileFilter() {

            @Override
            public boolean accept(java.io.File file) {
                return file.isDirectory() || WepsFileTypes.Management.accept(file) || WepsFileTypes.Rotation.accept(file);
            }
        };

        // Build a list of the files to process.
        while (alldirs.empty() == false) {
            currentDir = alldirs.pop();
            java.io.File fnames[] = currentDir.listFiles(filter);
            for (java.io.File fname : fnames) {
                try {
                    String dname = fname.getCanonicalPath();
                    if (fname.isDirectory() == false) {
                        db.addElement(dname);
                    } else {
                        if (recurse) {
                            TFile dirname = new TFile(dname);
                            alldirs.push(dirname);
                        }
                    }
                } catch (IOException e) {
                    //System.out.println("Error: " + e);
                }
            }
        }
        return 1;
    }//end of doRecursion()

    public void doUpdate(Component parent, List<String> db) {
        // Process all the files in db vector
        tempDb = db;
        this.parent = parent;
        //  //System.out.println("tempDb.size:"+tempDb.size());
        finalCount = 0;
        this.statDialog = new StatusDialog(parent, "Updating Management Files", this);
        this.statDialog.setMaxProgress(db.size());
        this.statDialog.setVisible(true);
        //Add a thread ID to track how many of these we are creating
        mainUpdateThread = new Thread(this, "XML Management Updater-" + THREAD_COUNTER++);
        mainUpdateThread.setPriority(1);
        mainUpdateThread.start();

    }//end of method doUpdate()

    @Override
    @SuppressWarnings("deprecation")
    public void run() {
        int count = 0;
        String skelfile = MCREWConfig.getDirectoryName(XMLConstants.smanagement_skeleton) + "\\temp.skel";
        SkelImportPanel skelimport = new SkelImportPanel(null, "Operation or crop not found",
                true, ManageData.WriteFileMode.UPDATE);
        String opDBDir = MCREWConfig.getDirectoryName(XMLConstants.soperation);
        String cropDBDir = MCREWConfig.getDirectoryName(XMLConstants.scrop);
        if (!skelimport.setDatabases(opDBDir, cropDBDir)) {
            //something didn't go right, let's quit
            return;
        }
        int totalFiles = tempDb.size();
        int toDelete;
        for (toDelete = 0; toDelete < tempDb.size(); toDelete++) {
            String s = tempDb.get(toDelete);

            // convert .man into a skeleton XML file in order to strip out all the crop and operation detail parameters
            SkeletonUpdater skel = new SkeletonUpdater();
            //Update the text field & progress bar in the status dialog
            this.statDialog.JTF_status.setText("Updating " + (toDelete + 1) + " out of " + totalFiles + " Management files.");
            this.statDialog.setProgress(toDelete + 1);
            this.statDialog.refresh();
            // This is what really does the conversion, read the management file and then write it out as a XML skel file
            if (skel.readWEPSManBrief(s)) {
                TFile manfile = new TFile(s);
                String basefile = manfile.getName();
                int end = basefile.lastIndexOf(".");
                if (end > 0) {
                    basefile = basefile.substring(0, end);
                }

                // This is a temp file in the skeleton directory with a __ at the beginning og the name
                skelfile = MCREWConfig.getDirectoryName(XMLConstants.smanagement_skeleton)
                        + TFile.separator + "__" + basefile + ".skel";
                if (skel.writeSkeletonXMLFile(skelfile)) {
                    // now use the skel-to-man code to build a full file with the updated params
                    if (!skelimport.setDatabases(opDBDir, cropDBDir)) {
                        //something didn't go right, let's quit
                        return;
                    }

                    // If there are operation or crop database files that are not found allow the user to fix these
                    if (skelimport.skel2man(skelfile, s)) {
                        count++;

                    } else {
                        if (JOptionPane.showConfirmDialog(parent,
                                "Do you want to stop updating management files?", "WEPS Information",
                                JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
                            TFile tempSkelFile = new TFile(skelfile);
                            if (tempSkelFile.exists()) {
                                try {
                                    tempSkelFile.rm();
                                } catch (IOException ex) {
                                    Exceptions.printStackTrace(ex);
                                }
                            }
                            break;
                        }
                    }//end of inner if-else block
                } else {
                    if (JOptionPane.showConfirmDialog(parent, "Could not load skeleton file: "
                            + skelfile + "\n\nDo you want to stop updating management files?",
                            "WEPS Information", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
                        break;
                    }
                }


            }//end of if(skel.readWEPSManBrief(s))
        }//end of for loop
        for(int index = 0; index < toDelete; index ++)
        {
            String s = tempDb.get(index);
            TFile manfile = new TFile(s);
            String basefile = manfile.getName();
            int end = basefile.lastIndexOf(".");
            if (end > 0) {
                basefile = basefile.substring(0, end);
            }
            skelfile = MCREWConfig.getDirectoryName(XMLConstants.smanagement_skeleton)
                    + TFile.separator + "__" + basefile + ".skel";
        //                java.io.File tempSkelFile = new java.io.File(skelfile);
            TFile tempSkelFile = new TFile(skelfile);
            if (tempSkelFile.exists()) {
                try{
//                    java.nio.file.Files.delete(tempSkelFile.toPath());
                tempSkelFile.rm();
                } catch (IOException ex) {
                    Exceptions.printStackTrace(ex);
                }
            }// cleanup the skel file used in the intermediate step
        }
        finalCount = count;
        //dispose of the status dialog
        statDialog.setVisible(false);
        statDialog.dispose();
        statDialog = null;
        //Display the total number of files updated.
        JOptionPane.showMessageDialog(parent, finalCount + " WEPS Management Files Updated",
                "WEPS Information", JOptionPane.INFORMATION_MESSAGE);

    }//end of run method
}//end of class XMLManagementUpdater

/* This class handles the behavior of the Status dialog.
 * This is the wrapper for the window that tracks the progress
 * of the update of the Management Files.
 ** @author  neha
 */
class StatusDialog extends usda.weru.mcrew.gui.StatusDialog_n {

    private static final long serialVersionUID = 1L;

    XMLManagementUpdater xmlMgmt;

    /** Creates a new instance of StatusDialog */
    public StatusDialog(Component parent, String title, XMLManagementUpdater xmlMgmtUpdater) {
        super((Frame) parent, false);
        this.xmlMgmt = xmlMgmtUpdater;
        setModal(false);
        setTitle(title);
        setLocation(100, 100);
        setVisible(true);
        JTF_status.setVisible(true);
        JPB_mcrew.setVisible(true);
        setVisible(true);
    }

    /*set the max number of files for the JProgressBar 
     *@param max
     */
    public void setMaxProgress(int max) {
        JPB_mcrew.setMaximum(max);
    }//end of setMaxProgress()

    public void setProgress(int current) {
        JPB_mcrew.setValue(current);
    }//end of setProgress

    public void setExpr(String expr) {
        JTF_status.setText(expr);
    }//end of setExpr

    public void refresh() {
        JP_main.revalidate();
    }
}//end of class StatusDialog

