/*
 * FindThread.java
 *
 * Created on 19 maggio 2004, 19.52
 */

package it.businesslogic.ireport.plugin.massivecompiler;

import javax.swing.table.*;
import java.io.*;
/**
 *
 * @author  Administrator
 */
public class FindThread implements Runnable {
    
    private MassiveCompilerFrame massiveCompilerFrame = null;
    private boolean stop = false;
    private Thread thread = null;
    
    public FindThread(MassiveCompilerFrame mcf)
    {
        this.massiveCompilerFrame = mcf;
        thread = new Thread(this);
    }
    
    public void stop()
    {
        stop = true;
    }
    
    public void start()
    {
        thread.start();
    }
    
    public void run() {
        if (massiveCompilerFrame == null)
        {
            return;
        }
        
        // Prepare the file search....
        
        DefaultTableModel dtm = (DefaultTableModel)massiveCompilerFrame.getFileTable().getModel();
        
        dtm.setRowCount(0);
        massiveCompilerFrame.getFileTable().updateUI();
        
        // Path
        File path = new File(massiveCompilerFrame.getFindDirectory());
        
        if (path == null || !path.exists() || path.isFile())
        {
            // Invalid conditions to search... 
            return;
        }
        
        if (!stop)  findFiles(path, massiveCompilerFrame.isSearchSubDirectory(),dtm);
        
        massiveCompilerFrame.finishedFind();
        return;
    }
    
    private int findFiles(File path, boolean recursive, DefaultTableModel tmodel)
    {
        if (stop) return 0;
        int count = 0;
        File[] files = path.listFiles();
        for (int i=0; i<files.length; ++i)
        {
            if (stop) return 0;
            if (files[i].isDirectory() && recursive)
            {
                count += findFiles( files[i], recursive,tmodel);
            }
            else
            {
                // Is the file a JasperReports source?
                if (files[i].getName().toLowerCase().endsWith(".xml") ||
                    files[i].getName().toLowerCase().endsWith(".jrxml"))
                {
                    // Ok, for me is a good file, get it !
                    FileEntry fe = new FileEntry();
                    fe.setFile( files[i] );
                    
                    // Looking for compiled and compilation version...
                    
                    
                    // ....
                    fe.setStatus( fe.STATUS_NOT_COMPILED );
                    tmodel.addRow( new Object[]{fe,fe,fe.decodeStatus(fe.getStatus())});
                    
                }
            }
        }
        
        return count;
    }
    
}
