package filemanager;

import com.vmx.Locale;
import java.io.IOException;
import javax.microedition.lcdui.*;

public class frmRename extends Form implements CommandListener
{
	private String oldFileName;
	private String newFileName;

	private TextField tfNewName;
	
	//private TextField tfOldName;
	private StringItem siOldName;

	private Object parent;
	private boolean isFolder = false;

	public frmRename(Object parent)
	{
		super("");
		setTitle(Locale.getString(this, Locale.RENAME));
		
		this.parent = parent;
		
		oldFileName = main.currentFile;

		if(oldFileName.endsWith("/")) //если выбранный файл - папка, убираем посл/ слеш
		{
			oldFileName = oldFileName.substring(0, oldFileName.length() - 1);
			isFolder = true;
		}

		tfNewName = new TemplateTextField(Locale.getString(this, Locale.NEW_NAME), oldFileName, 256, TextField.ANY);
		
		//tfOldName = new TextField(Locale.getString(this, Locale.OLD_NAME), oldFileName, 256, TextField.ANY);
		siOldName = new StringItem(Locale.getString(this, Locale.OLD_NAME) + ": ", oldFileName);
		
		append(tfNewName);
		append(siOldName);
		
		addCommand(new Command(Locale.getString(this, Locale.OK_CMD), Command.OK, 1));
		addCommand(new Command(Locale.getString(this, Locale.BACK_CMD), Command.BACK, 1));
		
		setCommandListener(this);
	}

	public void commandAction(Command command, Displayable displayable)
	{
		if(command.getCommandType() == Command.BACK)
		{
			main.dsp.setCurrent(parent);
		}
		else if(command.getCommandType() == Command.OK)
		{
			if(isFolder)
			{
				oldFileName += "/";
				newFileName = tfNewName.getString() + "/";
			}
			else
			{
				newFileName = tfNewName.getString();
			}

			if(newFileName.equals(oldFileName)) // имя не изменилось
			{
				main.dsp.setCurrent(parent);
			}
			else
			{
				if(filesystem.isFileExist(main.currentPath + newFileName))
				{
					main.showMessage(Locale.getString(this, Locale.ERROR), Locale.getString(this, Locale.NAME_EXIST_SELECT_ANOTHER), AlertType.WARNING, 3000, this);
				}
				else // переименовываем
				{
					try
					{
						filesystem.renameFile(main.currentPath, oldFileName, newFileName, null); //

						// если переименован, меняем имя и, если не папка, значок
						main.FileSelect.updateFileName(newFileName, main.FileSelect.getSelectedIndex());
						main.dsp.setCurrent(parent);
					}
					catch(IOException ioe) // не переименован
					{
						if(filesystem.isReadOnly(main.currentPath + main.currentFile)) // ReadOnly
						{
							main.showMessage(Locale.getString(this, Locale.ERROR), Locale.getString(this, Locale.FILE_READ_ONLY, main.currentPath + main.currentFile), AlertType.WARNING, 3000, parent);
						}
						else
						{
							main.showMessage(Locale.getString(this, Locale.ERROR), Locale.getString(this, Locale.NOT_RENAMED, main.currentPath + main.currentFile), AlertType.ERROR, 3000, parent);
						}
					}
				}
			}
		}
	}
}
