package jp.ac.osaka_u.ist.sel.sairi;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Calendar;

import android.util.Log;

public class TimeTableManager {

	private int year, date, time;
	private Calendar cal;

	public TimeTableManager() {

		cal = Calendar.getInstance();
		time = (cal.get(Calendar.HOUR_OF_DAY) * 100 + cal.get(Calendar.MINUTE));
		year = cal.get(Calendar.YEAR);
		date = (cal.get(Calendar.MONTH) + 1) * 100 + cal.get(Calendar.DAY_OF_MONTH);
	}
	

	public boolean isSuspension(InputStream fis) {
		String line;
		BufferedReader br = new BufferedReader(new InputStreamReader(fis));
		Log.d("DATE ", Integer.toString(date));
		try {
			while ((line = br.readLine()) != null) {
				String[] t = line.split(",");
				if (t[0].equals("ho")) {
					Log.d("HO ", t[1]);
					if (date == Integer.valueOf(t[1]) % 10000) {
						br.close();
						return true;
					}
				} else {

					Log.d(t[0], t[1] + " " + t[2]);
					if (date >= Integer.valueOf(t[1]) % 10000 && date <= Integer.valueOf(t[2]) % 10000) {
						br.close();
						return true;
					}
				}
			}
		} catch (IOException e) {
			// do nothing
		}
		return false;
	}

	public int getTime() {
		return time;
	}

	public void setTime(int time) {
		this.time = time;
	}

	public String getFormatedTime() {
		return (String.format("%1$02d", time / 100) + ":" + String.format("%1$02d", time % 100));
	}


	public String getYMD() {
		return year + "/" + String.format("%1$02d", date / 100) + "/" + String.format("%1$02d", date % 100);
	}


	public Bus bus(int from, int to, InputStream is) {

		String line;

		try {

			Log.d("BUS2 ", from + " " + to);

			BufferedReader br = new BufferedReader(new InputStreamReader(is));
			while ((line = br.readLine()) != null) {
				Log.d("BUS2 ", line);
				String[] t = line.split(",");
				if (Integer.valueOf(t[from]) >= time && Integer.valueOf(t[to]) != 0) {
					while ((line = br.readLine()) != null) {
						Log.d("BUS2 ", line);
						String[] t2 = line.split(",");
						if (!t2[from].equals("0") && !t2[to].equals("0")){
							return new Bus(t, from, to, false);
						}
					}
					return new Bus(t, from, to, true);
				}
			}

		} catch (NumberFormatException e) {
			// do nothing
		} catch (IOException e) {
			e.printStackTrace();
		}
		Log.d("BUS2 ", "NULL");
		return null;

	}
}
