package com.example.datecalc;

//import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;

public class dateCalc implements CommandListener {
	// private Display display;
	private recordStores rsDays, rsEvents;
	private static final int EVENT_LENGTH = 16; // Длина описания события в
												// символах
	private int EVENTS = 0; // текущее число событий
	private globalCalendar now;
	// private dateCalcCanvas dateCalcCanvas;
	// private monthCalendarForm monthForm;
	private calcForm calcForm;
	private numberForm numberForm;
	private drForm drForm;
	private dateDaysForm dateDaysForm;

	private static final int MODE_MENU = 0, // Режим меню
			MODE_EVENTS = 1; // Режим списка событий
	private int mode = MODE_MENU;
	private boolean isVoid = true; // Пуст ли список событий
	private boolean eventReplace = false; // Заменять ли событие в списке

	public int[][] days = { { 1, 0, 2001 }, { 1, 0, 2001 }, { 1, 0, 2001 },
			{ 1, 0, 2001 }, { 1, 0, 2001 }, { 1, 0, 2001 } };
	private String eventStr;
	private int eventDay, eventMonth, eventYear;

	private int selector = 0; // Выбор в меню
	private int eventNum = -1; // Выбор события

	private Command cmdExit = new Command("Выход", Command.BACK, 2);
	private Command cmdMenu = new Command("Назад", Command.BACK, 1);
	private Command cmdBack = new Command("Назад", Command.BACK, 1);
	private Command cmdAdd = new Command("Добавить", Command.ITEM, 3);
	private Command cmdShow = new Command("Смотреть", Command.ITEM, 3);
	private Command cmdChange = new Command("Изменить", Command.ITEM, 3);
	private Command cmdClear = new Command("Удалить", Command.ITEM, 3);
	private Command cmdGo = new Command("Ввод", Command.ITEM, 1);

	private static String[] mainMenuStr = { "Калькулятор дат", // calcForm
			"Номер дня/недели", // numberForm
			"Дата + дни", // dateDaysForm
			"Мои дни", // drForm
			"Мои события",
			/*
			 * "Текущее время", // dateCalcCanvas -> dateCalcTimer
			 * "Вечный календарь", // monthCalendarForm -> calendarCanvas
			 */"О программе" };

	private List mainMenu = new List("Дата и время", Choice.IMPLICIT,
			mainMenuStr, null);
	private List eventList = new List("События", Choice.IMPLICIT, mainMenuStr,
			null);
	private Form showEventForm = new Form("Событие");
	private StringItem showEventHdr, showEventDays, showEventTimes;
	private Form cnangeEventForm = new Form("Ввод события");
	private DateField eventDate;
	private TextField eventText;

	public dateCalc() {

		//mainMenu.setFont(Font.getFont(Font.FACE_MONOSPACE, Font.STYLE_ITALIC,
		//		Font.SIZE_LARGE));

		mainMenu.addCommand(cmdExit);
		mainMenu.setCommandListener(this);
	}

	public void startApp() {
		// display = Display.getDisplay(this);
		MainActivity.ma.display.setCurrent(mainMenu);
		now = new globalCalendar();

		rsDays = new recordStores(MainActivity.ma.display, "dateCalc_days",
				8 * 2);
		int n = rsDays.getNumRecords();
		String s;
		for (int i = 0; i < 6; i++) {
			s = rsDays.getRecord(i + 1);
			if ((n < 6) || (s == null)) {
				days[i][0] = now.getDay();
				days[i][1] = now.getMonth();
				days[i][2] = now.getYear();
			} else {
				days[i][0] = Integer.parseInt(s.substring(0, 2));
				days[i][1] = Integer.parseInt(s.substring(2, 4));
				days[i][2] = Integer.parseInt(s.substring(4));
			}
		}
		if (n < 6)
			EVENTS = 0;
		else
			EVENTS = days[4][0];

		rsEvents = new recordStores(MainActivity.ma.display, "dateCalc_events",
				(8 + EVENT_LENGTH) * 2);
		if (EVENTS < 1)
			createEventList();
		else {
			clearEventList();
			isVoid = false;
			int d0, m0, y0;
			for (int i = 0; i < EVENTS; i++) {
				s = rsEvents.getRecord(i + 1);
				if (s != null) {
					if (s.length() > 8)
						eventStr = s.substring(8) + " (";
					else
						eventStr = " (";
					d0 = Integer.parseInt(s.substring(0, 2));
					m0 = Integer.parseInt(s.substring(2, 4));
					y0 = Integer.parseInt(s.substring(4, 8));
					eventStr = eventStr + now.getDateStr(d0, m0, y0) + ")";
					eventList.append(eventStr, null);
				} else
					eventList.append("Пусто (01.01.2001, Пн)", null);
			}
		}

		initListHeader();
		eventList.addCommand(cmdMenu);
		eventList.addCommand(cmdShow);
		eventList.addCommand(cmdAdd);
		eventList.addCommand(cmdChange);
		eventList.addCommand(cmdClear);
		eventList.setCommandListener(this);

		showEventHdr = new StringItem("Событие:", "");
		showEventDays = new StringItem("Число дней:", "");
		showEventTimes = new StringItem("Разница дат:", "");
		showEventForm.append(showEventHdr);
		showEventForm.append(showEventDays);
		showEventForm.append(showEventTimes);
		showEventForm.addCommand(cmdBack);
		showEventForm.setCommandListener(this);

		eventDate = new DateField("Дата события", DateField.DATE);
		eventText = new TextField("Описание события", null, EVENT_LENGTH,
				TextField.ANY);
		cnangeEventForm.append(eventDate);
		cnangeEventForm.append(eventText);
		cnangeEventForm.addCommand(cmdBack);
		cnangeEventForm.addCommand(cmdGo);
		cnangeEventForm.setCommandListener(this);
	}

	public void pauseApp() {
	}

	public void destroyApp(boolean unconditional) {
		saveRecords();
	}

	public void initListHeader() {
		mainMenu.setTitle(now.globalDate());
	}

	public void saveRecords() {
		String s;
		int i;
		days[4][0] = EVENTS;
		for (i = 0; i < 6; i++) {
			s = "" + now.oNum(days[i][0]) + now.oNum(days[i][1])
					+ now.oNum4(days[i][2]);
			rsDays.setRecord(i + 1, s);
		}
		rsDays.closeRecords();
		if (rsEvents != null) {
			for (i = 0; i < EVENTS; i++) {
				getEventItems(i);
				rsEvents.setRecord(
						i + 1,
						"" + now.oNum(eventDay) + now.oNum(eventMonth)
								+ now.oNum4(eventYear) + eventStr);
			}
		}
		rsEvents.closeRecords();
		// notifyDestroyed();
		MainActivity.ma.closeApplication();
	}

	public void addEvent() {
		eventDate.setDate(now.initDateField(now.getDay(), now.getMonth(),
				now.getYear()));
		eventText.setString("");
		eventReplace = false;
		MainActivity.ma.display.setCurrent(cnangeEventForm);
	}

	public void clearEventList() {
		int i;
		do {
			i = eventList.size();
			if (i > 0)
				eventList.delete(0);
		} while (i > 0);
	}

	public void createEventList() {
		isVoid = true;
		EVENTS = 0;
		clearEventList();
		eventList.append("Список пуст", null);
	}

	public void getEventItems(int i) {
		String s = eventList.getString(i).trim();
		int sp = s.lastIndexOf('(') + 1;
		String dt = s.substring(sp);
		eventDay = Integer.parseInt(dt.substring(0, 2));
		eventMonth = Integer.parseInt(dt.substring(3, 5)) - 1;
		eventYear = Integer.parseInt(dt.substring(6, 10));
		eventStr = s.substring(0, sp - 1).trim();
	}

	public void showEvent() {
		eventNum = eventList.getSelectedIndex();
		getEventItems(eventNum);
		showEventHdr.setText(eventStr + " ("
				+ now.getDateStr(eventDay, eventMonth, eventYear) + ")");
		int k = now.kolDays(now.getDay(), now.getMonth(), now.getYear(),
				eventDay, eventMonth, eventYear);
		showEventDays.setText(k + "");
		showEventTimes.setText(now.kolTimes(now.getDay(), now.getMonth(),
				now.getYear(), eventDay, eventMonth, eventYear));
		MainActivity.ma.display.setCurrent(showEventForm);
	}

	public void commandAction(Command c, Displayable d) {
		initListHeader();
		if (c == cmdExit) {
			destroyApp(true);
		} else if (c == cmdMenu) {
			mode = MODE_MENU;
			MainActivity.ma.display.setCurrent(mainMenu);
		} else if (c == cmdBack) {
			MainActivity.ma.display.setCurrent(eventList);
		} else if ((c == cmdShow) && (isVoid == false)) {
			showEvent();
		} else if ((c == cmdChange) && (isVoid == false)) {
			eventNum = eventList.getSelectedIndex();
			getEventItems(eventNum);
			eventDate.setDate(now
					.initDateField(eventDay, eventMonth, eventYear));
			eventText.setString(eventStr);
			eventReplace = true;
			MainActivity.ma.display.setCurrent(cnangeEventForm);
		} else if (c == cmdAdd)
			addEvent();
		else if ((c == cmdClear) && (isVoid == false)) {
			eventNum = eventList.getSelectedIndex();
			EVENTS--;
			if (EVENTS > 0) {
				eventList.delete(eventNum);
				if (eventNum > 0)
					eventNum--;
				MainActivity.ma.display.setCurrent(eventList);
			} else {
				createEventList();
				mode = MODE_MENU;
				MainActivity.ma.display.setCurrent(mainMenu);
			}
		} else if (c == cmdGo) {
			int i = 0;
			int d0 = now.getDateFields(0, eventDate);
			int m0 = now.getDateFields(1, eventDate);
			int y0 = now.getDateFields(2, eventDate);
			String s0 = eventText.getString().trim();
			if (s0.compareTo("") == 0)
				s0 = "Событие";
			String si = s0 + " (" + now.getDateStr(d0, m0, y0) + ")";
			if (isVoid == true) {
				isVoid = false;
				eventNum = i = 0;
				eventList.set(0, si, null);
			} else {
				i = 0;
				while (i < EVENTS) {
					getEventItems(i);
					if (now.compareDates(d0, m0, y0, eventDay, eventMonth,
							eventYear) <= 0)
						break;
					i++;
				}
				if (eventReplace == false) {
					if (i < EVENTS)
						eventList.insert(i, si, null);
					else
						eventList.append(si, null);
				} else {
					if (i == eventNum)
						eventList.set(i, si, null);
					else {
						eventList.delete(eventNum);
						if (i == EVENTS)
							eventList.append(si, null);
						else {
							if (i > eventNum)
								i--;
							eventList.insert(i, si, null);
						}
					}
				}
			}
			if (eventReplace == false)
				EVENTS++;
			if (i < 0)
				i = 0;
			else if (i >= eventList.size())
				i = eventList.size() - 1;
			eventList.setSelectedIndex(i, true);
			MainActivity.ma.display.setCurrent(eventList);
		} else if (c == List.SELECT_COMMAND) {
			if (mode == MODE_MENU) {
				selector = mainMenu.getSelectedIndex();
				switch (selector) {
				case 0:
					if (calcForm != null) {
						calcForm.flag = false;
						calcForm = null;
					}

					calcForm = new calcForm(this, mainMenuStr[selector],
							days[0][0], days[0][1], days[0][2], days[1][0],
							days[1][1], days[1][2]);
					MainActivity.ma.display.setCurrent(calcForm);
					calcForm.starter();
					break;
				case 1:
					if (numberForm != null) {
						numberForm.flag = false;
						numberForm = null;
					}
					numberForm = new numberForm(this, mainMenuStr[selector],
							days[2][0], days[2][1], days[2][2]);
					MainActivity.ma.display.setCurrent(numberForm);
					numberForm.starter();
					break;
				case 2:
					if (dateDaysForm != null) {
						dateDaysForm.flag = false;
						dateDaysForm = null;
					}
					dateDaysForm = new dateDaysForm(this,
							mainMenuStr[selector], days[5][0], days[5][1],
							days[5][2]);
					MainActivity.ma.display.setCurrent(dateDaysForm);
					dateDaysForm.starter();
					break;
				case 3:
					if (drForm != null) {
						drForm.flag = false;
						drForm = null;
					}
					drForm = new drForm(this, mainMenuStr[selector],
							days[3][0], days[3][1], days[3][2]);
					MainActivity.ma.display.setCurrent(drForm);
					drForm.starter();
					break;
				case 4:
					mode = MODE_EVENTS;
					if (EVENTS > 0)
						MainActivity.ma.display.setCurrent(eventList);
					else
						addEvent();
					break;
				case 5:
					/*
					 * dateCalcCanvas = new dateCalcCanvas (this);
					 * display.setCurrent(dateCalcCanvas); break; case 6:
					 * monthForm = new monthCalendarForm
					 * (this,days[4][1],days[4][2]);
					 * display.setCurrent(monthForm); break; case 7:
					 */
					new Alert("Информация", "Калькулятор дат - считает количество дней между 2 любыми датами. Диапазон дат не ограничен календарем телефона (например, у меня в Siemens C65 этот диапазон - 1900-2033 годы), поэтому вводятся отдельно день, месяц и год.\n"
							+ "Номер дня/недели - показывает номер дня и недели в году для введенной даты.\n"
							+ "Дата + дни - складывает указанную дату и количество дней\n"
							+ "Мои дни - считает Ваш возраст в днях и число дней до ДР.\n"
							+ "Мои события - поддерживает список любых событий.\n"
							+
							// "Текущее время - идущие цифровые часы.\n"+
							// "Вечный календарь - календарь на выбранные месяц и год, выбор также не ограничен календарем телефона. Календарь можно листать джойстиком.\n"+
							"Все введенные Вами даты запоминаются программой.\n"
							+ "(С) PerS, pers@mail.ru, 2005\n"
							+ "Ported to Android/Blackberry10 by Salat-Cx65, 2013", null, AlertType.INFO).ShowAlert();
					
					break;
				}
			} else {
				showEvent();
			}
		}
	}

}