package ajcon.AppletExtractor;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;


public class ExtractionHandler {

    // private MainAction action;
    private ArrayList<String> appletSourcePaths;
    private String projectPath;
    private String sourceFilesPath;
    private String libFilesPath;
    private String configFileName;
    // org.apache.log4j.Logger logger;

    /*
    public ExtractionHandler(MainAction ma)
    {

    }
     */

    public ExtractionHandler(String configFileName, String projectPath)
    {
        this.configFileName = configFileName;
        appletSourcePaths = new ArrayList<String>();

        //projectPath = "comes from UI Component"
        this.projectPath = projectPath;
        try{
            BufferedReader cfgReader = new BufferedReader(new FileReader(projectPath + "\\" + configFileName));
            sourceFilesPath = cfgReader.readLine();
            libFilesPath = cfgReader.readLine();
   
        }
        catch(IOException ex)
        {
            ex.printStackTrace();
        }
    }

    public ArrayList<String> getAppletSourcePaths()
    {
        return appletSourcePaths;
    }

    public String getSourceFilesPath()
    {
        return sourceFilesPath;
    }

    public void parseAndExtractApplet(String rootPath)
    {
        try
        {
            File dir = new File(rootPath);
            String[] allFilesAndDirectories = dir.list();

           // System.out.println(allFilesAndDirectories.length);
            for(String s : allFilesAndDirectories)
            {
                
                if(s.endsWith(".java"))
                {
                    //System.out.println(s);
                    String className = s.substring(0,s.indexOf('.') - 1);
                    BufferedReader javaReader = new BufferedReader(new FileReader(rootPath + "\\" +s));

                    String line = "";
                    while(!line.startsWith("public"))
                    {
                        line = javaReader.readLine();
                    }

                    if(line.contains(className) && line.contains("extends") &&
                      (line.contains("JApplet") || line.contains("Applet")))
                    {
                        //System.out.println(rootPath + "\\" + s);
                        appletSourcePaths.add(rootPath + "\\" + s);
                    }
                }
                else if(new File(rootPath + "\\" +s).isDirectory())
                    parseAndExtractApplet(rootPath + "\\" + s);
            }
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }

    }


}
