package filemanager;

import com.one.Operation;
import java.util.*;
import java.io.*;
import com.one.RTEF;
import com.one.file.*;

/**
 * Поток шифрования файлов
 */
public class CryptThread extends Operation
{
	protected RTEF rtef;

	public CryptThread(String password)
	{
		rtef = new RTEF(password);
		Buffer.flattenBuffer();
	}
	
	/**
     * Функция, осуществляющая собственно шифрование
	 */
	public void run()
	{
		FileConnection fc = null;
		InputStream is = null;
		OutputStream os = null;
		
		try
		{
			Enumeration files;
			
			if(callback != null)
			{
				files = Buffer.getBuffer();
				int max = 0;
				
				while(files.hasMoreElements())
				{
					max += filesystem.getSize((String)files.nextElement(), true);
				}
				
				callback.setMax(max);
				callback.setProgress(0);
			}
			
			files = Buffer.getBuffer();
			
			int cp;
			String fname;
			
			while(enabled && files.hasMoreElements())
			{
				fname = (String)files.nextElement();
				
				if(callback != null)
				{
					callback.setText(fname); // fname.substring(fname.lastIndexOf('/') + 1));
				}
				
				fc = (FileConnection)Connector.open("file:///" + fname);
				is = fc.openInputStream();
				os = fc.openOutputStream();
				
				cp = is.available();
				
				rtef.crypt(is, os, callback);
				
				os.flush();
				os.close();
				is.close();
				fc.close();
				
				os = null;
				is = null;
				fc = null;
				System.gc();
				
				if(callback != null)
				{
					callback.progress(cp);
				}
			}
		}
		catch(Exception ex)
		{
			logError(ex);
			
			if(fc != null)
			{
				try
				{
					fc.close();
				}
				catch(Exception xx)
				{
				}
			}
		}
	}
	
//	private static void out(String s)
//	{
//		System.out.println("[CryptThread] " + s);
//	}
}
