package filemanager;

import com.classpath.hash.Sha160;
import com.classpath.hash.HashUtil;
import com.one.ArchiveContainer;
import com.vmx.keyConfig;
import com.one.ErrScreen;
import com.one.TextProcessor;
import com.one.file.Connector;
import com.vmx.AuxClass;
import javax.microedition.rms.*;
import java.io.*;
import java.util.Vector;
import java.util.Enumeration;

public class options
{
	// Версия настроек... Меняется, когда изменяется их структура в RMS
	public static final int OPTIONS_VERSION = 54;

	// Настройки
	public static int firstTime = 2;
	public static boolean showHidden = false;
	public static boolean openNotSupported = false;
	public static boolean noEffects = false;
	public static String language = "";
	public static boolean showErrors = true;
	public static int colorScheme = 0;
	public static boolean checkFileAttrib = false;
	public static boolean accurateDirCheck = false;
	public static int keyMap = -1;
	public static boolean clockMode = true;
	public static int textEnc = 0;
	public static int arcEnc = 0;
	public static boolean showMenuNum = true;
	public static String extColorScheme = "";
	public static boolean frameCursor = false;
	public static boolean rememberPath = true;
	public static boolean playAlertSounds = false;
	public static boolean swapSoftKeys = false;
	public static int listSortBy = 1;
	public static boolean listSortReverseOrder = false;
	public static boolean listSortIgnoreCase = true;
	public static boolean useFullMenu = false;
	public static boolean markMoveNext = true;
	public static boolean alterClockPos = false;
	public static int lightControlMode = 2;
	public static int screenTransform = 0;
	public static int keyVibraDuration = 0;
	public static int mmDelay = 1000;
	public static int mmThreshold = 100;
	public static float longScrollSpeed = 1;
	public static boolean ditherGradients = true;
	public static boolean alphaGradients = true;
	public static boolean fullNamesInFav = false;
	public static boolean fullNamesInBuf = true;
	public static boolean cacheCodePages = true;
	public static boolean largeFontInList = false;
	public static boolean largeFontInMenu = false;
	public static boolean exitFromDriveList = true;
	public static boolean unloadModules = false;
	public static int nfNameFormat = 0;
	
	// еще настройки

	// Избранное
	protected static Vector favorites;
	public static String[] favmodules = new String[10];

	static
	{
		for(int i = 0; i < favmodules.length; i++)
		{
			favmodules[i] = "";
		}
	}
	
	// Закладки
	protected static Vector bookmarks;
	
	protected static class BookMarkRecord
	{
		public String name;
		public int position;
	}

	public static final String EMPTY_HASH = HashUtil.toString((new Sha160()).digest());

	public static String launchPasswordHash = EMPTY_HASH;
	public static String optionsPasswordHash = EMPTY_HASH;
	
	/**
	 * Пустой конструктор
	 */
	public options()
	{
	}
	
	/**
	 * Сохранение настроек
	 */
	public static void saveOptions()
	{
		try
		{
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			DataOutputStream dos = new DataOutputStream(baos);
			
			dos.writeInt(OPTIONS_VERSION);
			dos.writeInt(firstTime);
			dos.writeBoolean(showHidden);
			dos.writeBoolean(openNotSupported);
			dos.writeBoolean(noEffects);
			dos.writeUTF(language);
			dos.writeBoolean(showErrors);
			dos.writeInt(colorScheme);
			dos.writeBoolean(checkFileAttrib);
			dos.writeBoolean(accurateDirCheck);
			dos.writeInt(keyMap);
			dos.writeBoolean(clockMode);
			dos.writeInt(textEnc);
			dos.writeInt(arcEnc);
			dos.writeBoolean(showMenuNum);
			dos.writeUTF(extColorScheme);
			dos.writeBoolean(frameCursor);
			dos.writeBoolean(rememberPath);
			dos.writeBoolean(playAlertSounds);
			dos.writeBoolean(swapSoftKeys);
			dos.writeInt(listSortBy);
			dos.writeBoolean(listSortReverseOrder);
			dos.writeBoolean(listSortIgnoreCase);
			dos.writeBoolean(useFullMenu);
			dos.writeBoolean(markMoveNext);
			dos.writeBoolean(alterClockPos);
			dos.writeInt(lightControlMode);
			dos.writeInt(screenTransform);
			dos.writeInt(keyVibraDuration);
			dos.writeInt(mmDelay);
			dos.writeInt(mmThreshold);
			dos.writeFloat(longScrollSpeed);
			dos.writeBoolean(ditherGradients);
			dos.writeBoolean(alphaGradients);
			dos.writeBoolean(fullNamesInFav);
			dos.writeBoolean(fullNamesInBuf);
			dos.writeBoolean(cacheCodePages);
			dos.writeBoolean(largeFontInList);
			dos.writeBoolean(largeFontInMenu);
			dos.writeBoolean(exitFromDriveList);
			dos.writeBoolean(unloadModules);
			dos.writeInt(nfNameFormat);

			dos.writeUTF(ErrScreen.getLogFileName());
			dos.writeBoolean(AuxClass.duplexFileAccess);
			dos.writeUTF(AuxClass.timeToFileNameFormat);
			dos.writeUTF(Connector.getTempFileDir());
			dos.writeBoolean(ArchiveContainer.virtualizeToRAM);
			dos.writeBoolean(TemplateTextField.useTemplates);

			keyConfig.writeConfig(dos);
			ColorScheme.writeSchemeData(dos);

			for(int i = 0; i < favmodules.length; i++)
			{
				dos.writeUTF(favmodules[i]);
			}
			
			byte[] data = baos.toByteArray();
			dos.close();
			
			RecordStore rs = RecordStore.openRecordStore(AuxClass.getStoreName(0), true);
			
			if(rs.getNumRecords() == 0)
			{
				rs.addRecord(data, 0, data.length);
			}
			else
			{
				rs.setRecord(1, data, 0, data.length);
			}
			
			rs.closeRecordStore();
		}
		catch(Exception e)
		{
			ErrScreen.showErrMsg(103, e);
		}
	}
	
	/**
     * Восстановить настройки
     */
	public static void restoreOptions()
	{
		try
		{
			RecordStore rs = RecordStore.openRecordStore(AuxClass.getStoreName(0), true);
			
			if(rs.getNumRecords() == 0)
			{
				rs.closeRecordStore();
				return;
			}
			
			DataInputStream dis = new DataInputStream(new ByteArrayInputStream(rs.getRecord(1)));
			rs.closeRecordStore();
			
			if(dis.readInt() != OPTIONS_VERSION)
			{
				// Что-то поменялось в структуре,
				// и восстановить старые настройки уже не получится.
				// Сбрасываем настройки на исходные.
				
				dis.close();
				resetOptions();
				
				return;
			}
			
			firstTime = dis.readInt(); // первый раз запущен
			showHidden = dis.readBoolean(); // показывать скрытые
			openNotSupported = dis.readBoolean(); // показывать неподдерживаемые
			noEffects = dis.readBoolean(); // без "подождите"
			language = dis.readUTF();
			showErrors = dis.readBoolean();
			colorScheme = dis.readInt();
			checkFileAttrib = dis.readBoolean();
			accurateDirCheck = dis.readBoolean();
			keyMap = dis.readInt();
			clockMode = dis.readBoolean();
			textEnc = dis.readInt();
			arcEnc = dis.readInt();
			showMenuNum = dis.readBoolean();
			extColorScheme = dis.readUTF();
			frameCursor = dis.readBoolean();
			rememberPath = dis.readBoolean();
			playAlertSounds = dis.readBoolean();
			swapSoftKeys = dis.readBoolean();
			listSortBy = dis.readInt();
			listSortReverseOrder = dis.readBoolean();
			listSortIgnoreCase = dis.readBoolean();
			useFullMenu = dis.readBoolean();
			markMoveNext = dis.readBoolean();
			alterClockPos = dis.readBoolean();
			lightControlMode = dis.readInt();
			screenTransform = dis.readInt();
			keyVibraDuration = dis.readInt();
			mmDelay = dis.readInt();
			mmThreshold = dis.readInt();
			longScrollSpeed = dis.readFloat();
			ditherGradients = dis.readBoolean();
			alphaGradients = dis.readBoolean();
			fullNamesInFav = dis.readBoolean();
			fullNamesInBuf = dis.readBoolean();
			cacheCodePages = dis.readBoolean();
			largeFontInList = dis.readBoolean();
			largeFontInMenu = dis.readBoolean();
			exitFromDriveList = dis.readBoolean();
			unloadModules = dis.readBoolean();
			nfNameFormat = dis.readInt();

			ErrScreen.setLogFileName(dis.readUTF());
			AuxClass.duplexFileAccess = dis.readBoolean();
			AuxClass.timeToFileNameFormat = dis.readUTF();
			Connector.setTempFileDir(dis.readUTF());
			ArchiveContainer.virtualizeToRAM = dis.readBoolean();
			TemplateTextField.useTemplates = dis.readBoolean();

			keyConfig.readConfig(dis);
			ColorScheme.readSchemeData(dis);

			for(int i = 0; i < favmodules.length; i++)
			{
				favmodules[i] = dis.readUTF();
			}
			
			dis.close();
		}
		catch(Exception e)
		{
			ErrScreen.showErrMsg(104, e);
		}
	}
	
	public static void resetOptions()
	{
		try
		{
			RecordStore.deleteRecordStore(AuxClass.getStoreName(0));
		}
		catch(Exception e)
		{
			ErrScreen.showErrMsg(105, e);
		}
	}

	public static void savePasswords()
	{
		try
		{
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			DataOutputStream dos = new DataOutputStream(baos);

			dos.writeUTF(launchPasswordHash);
			dos.writeUTF(optionsPasswordHash);

			byte[] data = baos.toByteArray();
			dos.close();

			RecordStore rs = RecordStore.openRecordStore(TextProcessor.byteArrayToString(new byte[] { 80, 97, 115, 115, 119, 111, 114, 100, 45, 83, 116, 111, 114, 97, 103, 101 }), true);

			if(rs.getNumRecords() == 0)
			{
				rs.addRecord(data, 0, data.length);
			}
			else
			{
				rs.setRecord(1, data, 0, data.length);
			}

			rs.closeRecordStore();
		}
		catch(Exception e)
		{
			//e.printStackTrace();
		}
	}

	public static void loadPasswords()
	{
		try
		{
			RecordStore rs = RecordStore.openRecordStore(TextProcessor.byteArrayToString(new byte[] { 80, 97, 115, 115, 119, 111, 114, 100, 45, 83, 116, 111, 114, 97, 103, 101 }), true);

			if(rs.getNumRecords() == 0)
			{
				rs.closeRecordStore();

				launchPasswordHash = main.loader.getAppProperty(TextProcessor.byteArrayToString(new byte[] { 76, 97, 117, 110, 99, 104, 45, 80, 97, 115, 115, 119, 111, 114, 100 }));
				optionsPasswordHash = main.loader.getAppProperty(TextProcessor.byteArrayToString(new byte[] { 79, 112, 116, 105, 111, 110, 115, 45, 80, 97, 115, 115, 119, 111, 114, 100 }));

				if(launchPasswordHash == null || launchPasswordHash.length() != EMPTY_HASH.length())
				{
					launchPasswordHash = EMPTY_HASH;
				}

				if(optionsPasswordHash == null || optionsPasswordHash.length() != EMPTY_HASH.length())
				{
					optionsPasswordHash = EMPTY_HASH;
				}
			}
			else
			{
				DataInputStream dis = new DataInputStream(new ByteArrayInputStream(rs.getRecord(1)));
				rs.closeRecordStore();

				launchPasswordHash = dis.readUTF();
				optionsPasswordHash = dis.readUTF();

				dis.close();
			}
		}
		catch(Exception e)
		{
			//e.printStackTrace();
		}

//		System.out.println(EMPTY_HASH);
//		System.out.println(launchPasswordHash);
//		System.out.println(settingsPasswordHash);
	}
	
	/**
     * Сохранение избранного
     */
	public static void saveFavorites()
	{
		if(favorites == null)
		{
			return;
		}

		try
		{
			RecordStore.deleteRecordStore(AuxClass.getStoreName(1));
		}
		catch(RecordStoreException e)
		{
		}
		
		try
		{
			RecordStore favoritesStore = RecordStore.openRecordStore(AuxClass.getStoreName(1), true);

			for(int i = 0; i < favorites.size(); i++)
			{
				try
				{
					ByteArrayOutputStream baos = new ByteArrayOutputStream();
					DataOutputStream dos = new DataOutputStream(baos);
					dos.writeUTF((String)favorites.elementAt(i));
					byte b[] = baos.toByteArray();
					favoritesStore.addRecord(b, 0, b.length);
				}
				catch(Exception e)
				{
				}
			}

			favoritesStore.closeRecordStore();
		}
		catch(Exception e)
		{
		}
	}
	
	/**
     * Получение избранного
     */
	public static Enumeration getFavorites()
	{
		if(favorites == null)
		{
			loadFavorites();
		}

		return favorites.elements();
	}
	
	/**
     * Добавление в избранное
     */
	public static void addFavorite(String nf)
	{
		if(favorites == null)
		{
			loadFavorites();
		}

		favorites.addElement(nf);
	}
	
	/**
	 * Удаление из избранного
	 */
	public static void deleteFavorite(String ff)
	{
		if(favorites == null)
		{
			loadFavorites();
		}

		favorites.removeElement(ff);
	}
	
	/**
     * Чтение строк из хранилища
     */
	public static void loadFavorites()
	{
		if(favorites == null)
		{
			favorites = new Vector();
		}
		else
		{
			favorites.removeAllElements();
		}

		try
		{
			RecordStore favoritesStore = RecordStore.openRecordStore(AuxClass.getStoreName(1), true);

			try
			{
				for(RecordEnumeration enumX = favoritesStore.enumerateRecords(null, null, true); enumX.hasNextElement(); )
				{
					int recId = enumX.nextRecordId();
					ByteArrayInputStream bais = new ByteArrayInputStream(favoritesStore.getRecord(recId));
					DataInputStream dis = new DataInputStream(bais);
					String in = dis.readUTF();
					favorites.addElement(in);
				}
			}
			catch(Exception e)
			{
			}

			favoritesStore.closeRecordStore();
		}
		catch(RecordStoreNotFoundException e)
		{
		}
		catch(RecordStoreException e)
		{
		}
	}
	
	public static void setBookMark(String name, int position)
	{
		if(bookmarks == null)
		{
			loadBookMarks();
		}

		BookMarkRecord bmr = null;
		
		for(int i = 0; i < bookmarks.size(); i++)
		{
			bmr = (BookMarkRecord)bookmarks.elementAt(i);
			
			if(bmr.name.equals(name))
			{
				bmr.position = position;
				return;
			}
		}
		
		bmr = new BookMarkRecord();
		bmr.name = name;
		bmr.position = position;
		
		bookmarks.addElement(bmr);
	}
	
	public static int getBookMark(String name)
	{
		if(bookmarks == null)
		{
			loadBookMarks();
		}

		BookMarkRecord bmr = null;
		int r = 0;
		
		for(int i = 0; i < bookmarks.size(); i++)
		{
			bmr = (BookMarkRecord)bookmarks.elementAt(i);
			
			if(bmr.name.equals(name))
			{
				r = bmr.position;
				break;
			}
		}
		
		return r;
	}
	
	/**
     * Сохранение закладок
     */
	public static void saveBookMarks()
	{
		if(bookmarks == null)
		{
			return;
		}

		try
		{
			RecordStore.deleteRecordStore(AuxClass.getStoreName(2));
		}
		catch(RecordStoreException e)
		{
		}
		
		try
		{
			RecordStore bookmarksStore = RecordStore.openRecordStore(AuxClass.getStoreName(2), true);
			
			for(int i = 0; i < bookmarks.size(); i++)
			{
				try
				{
					ByteArrayOutputStream baos = new ByteArrayOutputStream();
					DataOutputStream dos = new DataOutputStream(baos);
					
					dos.writeUTF(((BookMarkRecord)bookmarks.elementAt(i)).name);
					dos.writeInt(((BookMarkRecord)bookmarks.elementAt(i)).position);
					
					byte b[] = baos.toByteArray();
					bookmarksStore.addRecord(b, 0, b.length);
				}
				catch(Exception e)
				{
				}
			}
			
			bookmarksStore.closeRecordStore();
		}
		catch(Exception e)
		{
		}
	}
	
	/**
     * Чтение закладок из хранилища
     */
	public static void loadBookMarks()
	{
		if(bookmarks == null)
		{
			bookmarks = new Vector();
		}
		else
		{
			bookmarks.removeAllElements();
		}
		
		try
		{
			RecordStore bookmarksStore = RecordStore.openRecordStore(AuxClass.getStoreName(2), true);
			
			try
			{
				for(RecordEnumeration enumX = bookmarksStore.enumerateRecords(null, null, true); enumX.hasNextElement(); )
				{
					int recId = enumX.nextRecordId();
					ByteArrayInputStream bais = new ByteArrayInputStream(bookmarksStore.getRecord(recId));
					DataInputStream dis = new DataInputStream(bais);
					
					BookMarkRecord bmr = new BookMarkRecord();
					bmr.name = dis.readUTF();
					bmr.position = dis.readInt();
					
					bookmarks.addElement(bmr);
				}
			}
			catch(Exception e)
			{
			}
			
			bookmarksStore.closeRecordStore();
		}
		catch(RecordStoreNotFoundException e)
		{
		}
		catch(RecordStoreException e)
		{
		}
	}
	
//	private static void out(String s)
//	{
//		System.out.println("[options] " + s);
//	}
}
