package com.example.datecalc;

import javax.microedition.lcdui.*;

public class dateDaysForm extends Form implements CommandListener {
	private dateCalc dateCalc;
	private Display dpy;
	private Displayable prev;
	private globalCalendar now;
	//private errorForm er;

	private Command cmdMenu, cmdGo;
	private TextField day1, month1, year1, days;
	private StringItem otherStr;
	private int d1, m1, y1;
	private static int dt = 0;

	public dateDaysForm(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;
		cmdMenu = new Command("Назад", Command.BACK, 0);
		cmdGo = new Command("Ввод", Command.ITEM, 1);
		day1 = new TextField("День", d1 + "", 2, TextField.NUMERIC);
		month1 = new TextField("Месяц", m1 + 1 + "", 2, TextField.NUMERIC);
		year1 = new TextField("Год", y1 + "", 4, TextField.NUMERIC);
		days = new TextField("Количество дней:", dt + "", 6, TextField.NUMERIC);

		now = new globalCalendar();
		otherStr = new StringItem("Полученная дата:", now.datePlusDays(d1, m1,
				y1, dt));
		//append("\n");
		append(day1);
		append(month1);
		append(year1);
		append(days);
		append(otherStr);
		addCommand(cmdMenu);
		// addCommand(cmdGo);
		setCommandListener(this);
		//new Thread(this).start();
	}


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

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

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

				}
			}
		}).start();
	}

	boolean flag = true;


	public void commandAction(Command c, Displayable d) {
		//er = new errorForm(dpy, "Ошибка");
		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{
			
			if (now.correctDate(Integer.parseInt(day1.getString()), Integer.parseInt(month1.getString()) - 1, Integer.parseInt(year1.getString())) == false) {
				
				new Alert("Ошибка", "Дата " + now.getDMYDate(Integer.parseInt(day1.getString()), Integer.parseInt(month1.getString()) - 1, Integer.parseInt(year1.getString())) + " некорректна!", null, AlertType.ERROR).ShowAlert();
				day1.setString(String.valueOf(d1));
				month1.setString(String.valueOf(m1+1));
				year1.setString(String.valueOf(y1));
			} else {
				d1 = Integer.parseInt(day1.getString());
				m1 = Integer.parseInt(month1.getString()) - 1;
				y1 = Integer.parseInt(year1.getString());
				dt = Integer.parseInt(days.getString());
				otherStr.setText(now.datePlusDays(d1, m1, y1, dt));
				dateCalc.days[5][0] = d1;
				dateCalc.days[5][1] = m1;
				dateCalc.days[5][2] = y1;
			}
				} catch (Exception ex){}
			}});
		}
	}

}