package filemanager;

import com.one.Operation;
import com.one.ModuleRegistry;
import java.util.Enumeration;
import com.one.StringPattern;
import com.vmx.AuxClass;

public class SearchThread extends Operation
{
	protected StringPattern pattern;
	protected String path;
	protected boolean recursive;
	protected boolean archives;
	
	public SearchThread(StringPattern pattern, String path, boolean recursive, boolean archives)
	{
		this.pattern = pattern;
		this.path = path;
		this.recursive = recursive;
		this.archives = archives;

		clear = false;
	}
	
	public void run()
	{
		if(callback != null)
		{
			callback.setMax(1);
			callback.setProgress(0);
			callback.setPercentMode(false);
		}
		
		if(path == null || path.length() == 0)
		{
			Enumeration roots = filesystem.listRoots();

			if(roots != null)
			{
				while(enabled && roots.hasMoreElements())
				{
					search(pattern, (String)roots.nextElement());
				}
			}
		}
		else
		{
			search(pattern, path);
		}

		main.oldPath = main.currentPath;
		main.oldFile = main.currentFile;

		main.currentPath = "buf:/";
		main.currentFile = "";
	}
	
	protected void search(StringPattern pattern, String path)
	{
		if(!enabled)
		{
			return;
		}

		String file, fullname;
		
		if(callback != null)
		{
//			file = path.substring(0, path.length() - 1);
//			callback.setText(file.substring(file.lastIndexOf('/') + 1));
			callback.setText(path);
		}
		
		Enumeration files = filesystem.list(path, options.showHidden);

		if(files == null)
		{
			return;
		}
		
		while(files.hasMoreElements())
		{
			file = (String)files.nextElement();
			fullname = path + file;

			if(pattern.matchesWith(file))
			{
				Buffer.add(fullname, false);

				if(callback != null)
				{
					callback.progress(1);
				}
			}

			if(callback != null)
			{
				callback.rise(1);
			}

			if(recursive)
			{
				if(filesystem.isDir(fullname))
				{
					search(pattern, fullname);
				}
				else if(archives && ModuleRegistry.getAction(AuxClass.getFileExtension(fullname)) == ModuleRegistry.ACTION_EXPLORE)
				{
					search(pattern, fullname + "/");
				}
			}
		}
	}
}
