package filemanager;

import javax.microedition.lcdui.*;
import javax.microedition.rms.*;
import java.io.*;
import com.one.*;
import com.vmx.AuxClass;

/**
 * Класс управления панелями.
 * На панелях может быть не только FileSelect,
 * но и плеер, просмотр текста и т. д.
 */
public class PanelManager
{
	protected String[] currpath;
	protected String[] currfile;
	protected Object[] currdisp;
	protected int[] associat;
	protected String[] currname;
	
	protected DisplayManager dsp;
	protected int pcount;
	protected int currpanel, prevpanel;
	protected int prevpanelreq;
	
	public PanelManager(DisplayManager dsp, int pcount)
	{
		this.dsp = dsp;
		this.pcount = pcount;
		
		currpath = new String[pcount];
		currfile = new String[pcount];
		currdisp = new Object[pcount];
		associat = new int[pcount];
		currname = new String[pcount];
		
		for(int i = 0; i < pcount; i++)
		{
			currpath[i] = "";
			currfile[i] = "";
			currdisp[i] = main.FileSelect;
			associat[i] = -1;
			currname[i] = "";
		}
		
		currpanel = 0;
		prevpanel = pcount > 1 ? currpanel + 1 : currpanel;
		prevpanelreq = -1;
	}
	
	/**
	 * Сохранение данных панелей.
	 * Сохраняется только путь и имя текущего файла.
	 */
	public void savePanels()
	{
        try
        {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            DataOutputStream dos = new DataOutputStream(baos);

            dos.writeInt(pcount);
            dos.writeInt(currpanel);
            dos.writeInt(prevpanel);

            for(int i = 0; i < pcount; i++)
            {
                dos.writeUTF(currpath[i]);
                dos.writeUTF(currfile[i]);
            }

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

            RecordStore rs = RecordStore.openRecordStore(AuxClass.getStoreName(3), 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(101, e);
        }

		//printPanelData();
	}
	
	/**
     * Восстановить данные панелей.
     */
	public void restorePanels()
	{
        try
        {
            RecordStore rs = RecordStore.openRecordStore(AuxClass.getStoreName(3), true);

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

            DataInputStream dis = new DataInputStream(new ByteArrayInputStream(rs.getRecord(1)));

            int count = dis.readInt();

            if(count > pcount)
            {
                count = pcount;
            }

            currpanel = dis.readInt();
            prevpanel = dis.readInt();

            if(currpanel < 0)
            {
                currpanel = 0;
            }
            else if(currpanel >= pcount)
            {
                currpanel = pcount - 1;
            }

            if(prevpanel < 0)
            {
                prevpanel = 0;
            }
            else if(prevpanel >= pcount)
            {
                prevpanel = pcount - 1;
            }

            for(int i = 0; i < count; i++)
            {
                currpath[i] = dis.readUTF();
                currfile[i] = dis.readUTF();
            }

            dis.close();

            rs.closeRecordStore();
        }
        catch(Exception e)
        {
            ErrScreen.showErrMsg(102, e);
        }

		//printPanelData();
	}

//	public void printPanelData()
//	{
//		System.out.println();
//		System.out.println("Current panel: " + (currpanel + 1));
//		System.out.println("Previous panel: " + (prevpanel + 1));
//		System.out.println();
//
//		for(int i = 0; i < pcount; i++)
//		{
//			System.out.println("Panel " + (i + 1) + ": '" + currpath[i] + currfile[i] + "', " + currdisp[i].getClass().getName() + ", associated with " + (associat[i] + 1));
//		}
//
//		System.out.println();
//	}
	
	public void storePanel(int panel)
	{
		currpath[panel] = main.currentPath;
		currfile[panel] = main.currentFile;
		currdisp[panel] = dsp.getCurrent();
	}
	
	public void showPanel(int panel)
	{
		main.currentPath = currpath[panel];
		main.currentFile = currfile[panel];
		
		if(currdisp[panel] == main.FileSelect)
		{
			main.FileSelect.showWait(currfile[panel]);
		}
		else
		{
			dsp.setCurrent(currdisp[panel]);
		}
	}

	public void setPanelName(int panel, String name)
	{
		currname[panel] = name;
	}

	public String getPanelName(int panel)
	{
		return currname[panel];
	}

	public String getCurrentFileName(int panel)
	{
		if(currdisp[panel] == main.FileSelect)
		{
			return currpath[panel];
		}
		else
		{
			return currpath[panel] + currfile[panel];
		}
	}
	
	/**
	 * Возврат к FileSelect
	 */
	public void ret()
	{
		if(associat[currpanel] >= 0)
		{
			// если с этой панелью какая-то была связана,
			// переносим ее на эту
			int panel = associat[currpanel];

			currpath[currpanel] = currpath[panel];
			currfile[currpanel] = currfile[panel];
			currdisp[currpanel] = currdisp[panel];
			associat[currpanel] = associat[panel];
			currname[currpanel] = currname[panel];

			// а связанную возвращаем в исходное состояние
			currpath[panel] = "";
			currfile[panel] = "";
			currdisp[panel] = main.FileSelect;
			associat[panel] = -1;
			currname[panel] = "";

			showPanel(currpanel);
		}
		else
		{
			setCurrent(main.FileSelect, currpanel);
		}
	}
	
	/**
	 * Показываем что-нибудь на заданной панели
	 */
	public void setCurrent(Object dp, int panel)
	{
		if(dp != main.wait && dp != main.FileSelect)
		{
			deassociate(panel);
		}
		else
		{
			currname[panel] = "";
		}
		
		currdisp[panel] = dp;
		
		if(panel == currpanel)
		{
			dsp.setCurrent(dp);
		}
	}
	
	/**
	 * Показываем что-нибудь на текущей панели
	 */
	public void setCurrent(Object dp)
	{
		if(dp != main.wait && dp != main.FileSelect)
		{
			deassociate(currpanel);
		}
		else
		{
			currname[currpanel] = "";
		}
		
		currdisp[currpanel] = dp;
		
		dsp.setCurrent(dp);
	}
	
	public void setCurrent(Alert al, Object dp, int panel)
	{
		if(dp != main.wait && dp != main.FileSelect)
		{
			deassociate(panel);
		}
		else
		{
			currname[panel] = "";
		}
		
		currdisp[panel] = dp;
		
		dsp.setCurrent(al, currdisp[currpanel]);
	}
	
	public void setCurrent(AutoAdvanceScreen al, Object dp, int panel)
	{
		if(dp != main.wait && dp != main.FileSelect)
		{
			deassociate(panel);
		}
		else
		{
			currname[panel] = "";
		}
		
		currdisp[panel] = dp;
		
		dsp.setCurrent(al, currdisp[currpanel]);
	}
	
	/**
	 * Показать панель nextpanel
	 */
	public void changePanel(int nextpanel)
	{
		if(nextpanel < 0 || nextpanel >= pcount)
		{
			return;
		}
		
		if(nextpanel != currpanel)
		{
			storePanel(currpanel);
			
			prevpanel = currpanel;
			currpanel = nextpanel;
		}
		
		showPanel(currpanel);
	}
	
	/**
	 * Показать следующую панель
	 */
	public void showNextPanel()
	{
		storePanel(currpanel);
		
		prevpanel = currpanel;
		
		if(++currpanel >= pcount)
		{
			currpanel = 0;
		}
		
		showPanel(currpanel);
	}
	
	/**
	 * Показать предыдущую панель
	 */
	public void showPrevPanel()
	{
		storePanel(currpanel);
		
		prevpanel = currpanel;
		
		if(--currpanel < 0)
		{
			currpanel = pcount - 1;
		}
		
		showPanel(currpanel);
	}
	
	public void showNextFreePanel()
	{
		storePanel(currpanel);
		
		prevpanel = currpanel;
		
		do
		{
			if(++currpanel >= pcount)
			{
				currpanel = 0;
			}
			
			if(currdisp[currpanel] == main.FileSelect)
			{
				break;
			}
		} while(currpanel != prevpanel);
		
		showPanel(currpanel);
	}
	
	public void showPrevFreePanel()
	{
		storePanel(currpanel);
		
		prevpanel = currpanel;
		
		do
		{
			if(--currpanel < 0)
			{
				currpanel = pcount - 1;
			}
			
			if(currdisp[currpanel] == main.FileSelect)
			{
				break;
			}
		} while(currpanel != prevpanel);
		
		showPanel(currpanel);
	}
	
	/**
	 * Свернуть текущую панель - скопировать путь в другую
	 */
	public void minimizePanel()
	{
		storePanel(currpanel);
		
		prevpanel = currpanel;
		
		if(associat[currpanel] < 0)
		{
			associat[currpanel] = newPanel();
			
			currpath[associat[currpanel]] = currpath[currpanel];
			currfile[associat[currpanel]] = currfile[currpanel];
		}
		
		currpanel = associat[currpanel];
		showPanel(currpanel);
	}
	
	public void updateAssociation(int panel, String filename)
	{
		if(filename == null)
		{
			currpath[panel] = main.currentPath;
			currfile[panel] = main.currentFile;
			
			return;
		}
		
		int index = filename.lastIndexOf('/', filename.length() - 2) + 1;

		if(index > 0)
		{
			currpath[panel] = filename.substring(0, index);
			currfile[panel] = filename.substring(index);
		}
		else
		{
			currpath[panel] = "";
			currfile[panel] = filename;
		}
	}
	
	protected void deassociate(int panel)
	{
		for(int i = 0; i < pcount; i++)
		{
			if(associat[i] == panel)
			{
				associat[i] = -1;
			}
		}
	}
	
	/**
	 * Узнать номер текущей панели
	 */
	public int currentPanel()
	{
		return currpanel;
	}
	
	/**
	 * Узнать общее число панелей
	 */
	public int panelsCount()
	{
		return pcount;
	}
	
	/**
	 * Узнать номер предыдущей панели
	 */
	public int prevPanel()
	{
		return prevpanel;
	}
	
	/**
	 * Найти незанятую панель (на которой отображается FileSelect)
	 */
	public int newPanel()
	{
		for(int i = 0; i < pcount; i++)
		{
			if(currdisp[i] == main.FileSelect && currpath[i].length() == 0)
			{
				return i;
			}
		}
		
		return prevpanel;
	}
	
	public boolean isShown(Displayable dp)
	{
		return dsp.getCurrent() == dp;
	}
	
//	/**
//	 * Подготовка к открытию файла filename из панели panel
//	 */
//	public void requirePanel(int panel) throws Exception
//	{
//		if(panel < 0 || panel >= pcount || panel == currpanel)
//		{
//			return;
//		}
//
//		storePanel(currpanel);
//
//		prevpanelreq = currpanel;
//		currpanel = panel;
//
//		main.FileSelect.lock();
//
//		/*
//		int index = filename.lastIndexOf('/') + 1;
//
//		main.currentPath = filename.substring(0, index);
//		main.currentFile = filename.substring(index);
//		*/
//
//		main.currentPath = currpath[currpanel];
//		main.currentFile = currfile[currpanel];
//
//		main.FileSelect.list(main.currentFile);
//	}
//
//	/**
//	 * Завершение процедуры открытия файла
//	 */
//	public void releaseRequiredPanel()
//	{
//		main.FileSelect.unlock();
//
//		if(prevpanelreq < 0 || prevpanelreq >= pcount)
//		{
//			return;
//		}
//
//		currpanel = prevpanelreq;
//		prevpanelreq = -1;
//
//		showPanel(currpanel);
//	}
	
//	private static void out(String s)
//	{
//		System.out.println("[PanelManager] " + s);
//	}
}
