package filemanager;

import com.classpath.hash.HashUtil;
import com.classpath.hash.MessageDigest;
import com.classpath.hash.Sha160;
import com.vmx.Locale;
import com.vmx.StringEncoder;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.TextField;

public class frmPassword extends Form implements CommandListener
{
	protected MessageDigest md;
	protected String hash;

	protected TextField tf;
	protected boolean result;

	protected final Object waiter = new Object();

	public frmPassword(String msg, String hash)
	{
		super("");
		setTitle(Locale.getString(this, Locale.PASSWORD_REQUIRED));

		if(msg != null)
		{
			append(msg);
		}

		tf = new TextField(Locale.getString(this, Locale.ENTER_PASSWORD), "", 1024, TextField.PASSWORD);
		append(tf);

		addCommand(new Command(Locale.getString(this, Locale.OK_CMD), Command.OK, 1));
		addCommand(new Command(Locale.getString(this, Locale.CANCEL_CMD), Command.CANCEL, 2));
		setCommandListener(this);

		this.md = new Sha160();
		this.hash = hash;
	}

	public boolean modalResult()
	{
		synchronized(waiter)
		{
			try
			{
				waiter.wait();
			}
			catch(InterruptedException ie)
			{
			}
		}

		return result;
	}

	public void setResult(boolean r)
	{
		result = r;

		synchronized(waiter)
		{
			waiter.notifyAll();
		}
	}

	public boolean testPassword(String password)
	{
		md.update(StringEncoder.encodeString(password, StringEncoder.ENC_DEFAULT));
		return HashUtil.toString(md.digest()).equals(hash);
	}

	public void commandAction(Command c, Displayable dp)
	{
		if(c.getCommandType() == Command.OK)
		{
			if(testPassword(tf.getString()))
			{
				setResult(true);
			}
			else
			{
				main.showMessage(Locale.getString(this, Locale.ERROR), Locale.getString(this, Locale.INCORRECT_PASSWORD), AlertType.WARNING, 1500, this);
			}
		}
		else
		{
			setResult(false);
		}
	}
}