package modules;

import com.vmx.Locale;
import com.vmx.StringEncoder;
import javax.microedition.lcdui.*;
import com.one.file.*;
import java.io.*;
import com.one.*;
import filemanager.TemplateTextField;
import filemanager.main;
import java.util.Enumeration;

/**
 * Форма-редактор ID3v1-тегов MP3
 */
public class id3Editor implements Application, CommandListener
{
	public static String[] GENRES;

	protected Object parent;
	protected FileConnection fc;
	protected long tagpos;

	protected TextField tfTitle,
						tfArtist,
						tfAlbum,
						tfYear,
						tfComment,
						tfTrackNumber;

	protected ChoiceGroup cgGenre;

	public void openFile(String filename, PlayList filelist) throws IOException
	{
		fc = (FileConnection)Connector.open("file:///" + filename);
		tagpos = fc.fileSize();

		byte[] tag = null;
		int songnum = 1;
		int genre = 0;

		if(tagpos > 128)
		{
			InputStream is = fc.openInputStream();
			tag = new byte[128];
			
			tagpos -= 128;

			is.skip(tagpos);
			is.read(tag);
			is.close();

			if(getFromTag(tag, 0, 3).equals("TAG"))
			{
				songnum = (int)tag[126] & 0xFF;
				genre = (int)tag[127] & 0xFF;
			}
			else
			{
				tagpos += 128;
				tag = null;
			}
		}

		int year = 0;

		try
		{
			year = Integer.parseInt(getFromTag(tag, 93, 4).trim());
		}
		catch(NumberFormatException nfe)
		{
		}

		tfTitle = new TemplateTextField(Locale.getString(this, Locale.ID3_SONG), getFromTag(tag, 3, 30), 30, TextField.ANY);
		tfArtist = new TemplateTextField(Locale.getString(this, Locale.ID3_ARTIST), getFromTag(tag, 33, 30), 30, TextField.ANY);
		tfAlbum = new TemplateTextField(Locale.getString(this, Locale.ID3_ALBUM), getFromTag(tag, 63, 30), 30, TextField.ANY);
		tfYear = new TextField(Locale.getString(this, Locale.ID3_YEAR), Integer.toString(year), 4, TextField.NUMERIC);
		tfComment = new TemplateTextField(Locale.getString(this, Locale.ID3_COMMENT), getFromTag(tag, 97, 28), 28, TextField.ANY);
		tfTrackNumber = new TextField(Locale.getString(this, Locale.ID3_TRACKNUM), Integer.toString(songnum), 3, TextField.NUMERIC);

		if(GENRES == null)
		{
			loadGenres();
		}

		if(cgGenre == null)
		{
			cgGenre = new ChoiceGroup(Locale.getString(this, Locale.ID3_GENRE), Choice.POPUP, GENRES, null);
		}

		if(genre < 0 || genre >= GENRES.length)
		{
			genre = 0;
		}

		cgGenre.setSelectedIndex(genre, true);

		Form form = new Form(Locale.getString(this, Locale.TAG_EDITOR));

		form.append(tfTitle);
		form.append(tfArtist);
		form.append(tfAlbum);
		form.append(tfYear);
		form.append(tfComment);
		form.append(tfTrackNumber);
		form.append(cgGenre);

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

		parent = main.dsp.getCurrent();
		main.dsp.setCurrent(form);
	}

	/**
	 * Обработчик команд
	 */
	public void commandAction(Command c, Displayable d)
	{
		if(c.getCommandType() == Command.OK)
		{
			byte[] tag = new byte[128];

			setToTag(tag, "TAG", 0, 3);

			setToTag(tag, tfTitle.getString(), 3, 30);
			setToTag(tag, tfArtist.getString(), 33, 30);
			setToTag(tag, tfAlbum.getString(), 63, 30);
			setToTag(tag, tfYear.getString(), 93, 4);
			setToTag(tag, tfComment.getString(), 97, 28);

			tag[125] = 0;

			try
			{
				tag[126] = (byte)Integer.parseInt(tfTrackNumber.getString().trim());
			}
			catch(NumberFormatException nfe)
			{
				tag[126] = 1;
			}
			
			tag[127] = (byte)cgGenre.getSelectedIndex();

			try
			{
				OutputStream os = fc.openOutputStream(tagpos);

				os.write(tag);
				os.close();
				
				fc.close();
			}
			catch(Exception x)
			{
				ErrScreen.showErrMsg(125, x);
			}
		}

		main.dsp.setCurrent(parent);
	}

	/**
	 * Взять кусок тега и сделать строкой
	 */
	protected static String getFromTag(byte[] tag, int off, int len)
	{
		if(tag == null)
		{
			return "";
		}

		int end = off + len - 1;
		for(; end >= off && (tag[end] == 0 || tag[end] == ' '); end--);

		return StringEncoder.decodeString(tag, off, end - off + 1, StringEncoder.ENC_DEFAULT);
	}

	/**
	 * Записать строку в кусок тега
	 */
	protected static void setToTag(byte[] tag, String s, int off, int len)
	{
		byte[] bs = StringEncoder.encodeString(s, StringEncoder.ENC_DEFAULT);

		int pos = 0;

		for(; pos < bs.length && pos < len; pos++)
		{
			tag[off + pos] = bs[pos];
		}

		for(; pos < len; pos++)
		{
			tag[off + pos] = 0;
		}
	}

	public static void loadGenres() throws IOException
	{
		IniFile ini = new IniFile("/config/genres.ini", false);

		String section = (String)ini.listSections().nextElement();
		GENRES = new String[Integer.parseInt(section.substring(1, section.length() - 1).trim())];

		Enumeration keys = ini.listKeys(section);
		String key, value;

		while(keys.hasMoreElements())
		{
			key = (String)keys.nextElement();
			value = (String)ini.getRecord(section, key);

			try
			{
				GENRES[Integer.parseInt(key)] = value;
			}
			catch(Exception e)
			{
				System.out.println(e.toString() + " because of " + key + ", " + value);
			}
		}
	}
}
