package com.example.datecalc;

import javax.microedition.lcdui.*;

public class drForm extends Form implements CommandListener {
	private dateCalc dateCalc;
	private Display dpy;
	private Displayable prev;
	private globalCalendar now;

	private Command cmdMenu, cmdGo;
	private DateField date1;
	private StringItem dateStr, nextStr;
	private int d1, m1, y1, d2, m2, y2, i, y0;
	private static String drString = "С днем рождения Вас!";

	public drForm(dateCalc dateCalc, String hdr, int d1, int m1, int y1) {
		super(hdr);
		this.dateCalc = dateCalc;
		dpy = MainActivity.ma.display;
		prev = dpy.getCurrent();
		this.d1 = d1;
		this.m1 = m1;
		this.y1 = y1;
		now = new globalCalendar();
		d2 = now.getDay();
		m2 = now.getMonth();
		y2 = now.getYear();

		cmdMenu = new Command("Назад", Command.BACK, 0);
		cmdGo = new Command("Ввод", Command.ITEM, 1);
		date1 = new DateField("Ваш день рождения", DateField.DATE);

		date1.setDate(now.initDateField(d1, m1, y1));
		dateStr = new StringItem("Ваш возраст в днях:", ""
				+ now.kolDays(d1, m1, y1, d2, m2, y2));
		i = now.compareDates(d1, m1, y2, d2, m2, y2);
		if (i < 0)
			y0 = y2 + 1;
		else
			y0 = y2;
		nextStr = new StringItem("Дней до Вашего ДР:", ""
				+ now.kolDays(d2, m2, y2, d1, m1, y0));
		if (i == 0)
			nextStr.setText(drString);
		// append("\n");
		append(date1);
		append(dateStr);
		append(nextStr);
		addCommand(cmdMenu);
		// addCommand(cmdGo);
		setCommandListener(this);

	}

	public void starter() {
		new Thread(new Runnable(){
			public void run() {
				while (flag) {

					try {
						if (dpy.getCurrent() != drForm.this){
							flag = false;
							return;
							}
						Thread.sleep(100);						
						commandAction(cmdGo, drForm.this);

					} catch (Exception ex) {
						ex.printStackTrace();
					}

				}
			}
		}).start();
	}


	boolean flag = true;


	public void commandAction(Command c, Displayable d) {
		if (c == cmdMenu) {
			flag = false;
			dpy.setCurrent(prev);
			System.out.println("skip to prev screen");

		} else if (c == cmdGo) {
			UIGlobal.APP_HANDLER.post( new Runnable() { public void run(){
				try{
			d1 = now.getDateFields(0, date1);
			m1 = now.getDateFields(1, date1);
			y1 = now.getDateFields(2, date1);
			dateStr.setText("" + now.kolDays(d1, m1, y1, d2, m2, y2));
			dateCalc.days[3][0] = d1;
			dateCalc.days[3][1] = m1;
			dateCalc.days[3][2] = y1;
			i = now.compareDates(d1, m1, y2, d2, m2, y2);
			if (i == 0)
				nextStr.setText(drString);
			else {
				if (i < 0)
					y0 = y2 + 1;
				else
					y0 = y2;
				nextStr.setText("" + now.kolDays(d2, m2, y2, d1, m1, y0));
			}
				} catch (Exception ex){}
			}});
		}
	}

}