package com.yuji.ec.service;

import java.util.Calendar;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.widget.Toast;

import com.yuji.ec.Initialize;
import com.yuji.ec.common.Constant;
import com.yuji.ec.utility.DateUtil;
import com.yuji.ec.utility.Debug;
import com.yuji.ec.utility.EditPrefUtil;
import com.yuji.ec.utility.NetworkUtil;
import com.yuji.ec.utility.NoteUpdator;

public class NoteUpdatorService extends Service {
	private static final boolean DEBUG = false;

	public class KitchenTimerBinder extends Binder {
		public NoteUpdatorService getService() {
			return NoteUpdatorService.this;
		}
	}

	public static final String ACTION = "NoteUpdatorService";
	public static final String ACTION_START = "START";
	private static final int DS = 60;
	private EditPrefUtil pref = new EditPrefUtil(this);
	private KitchenTimerBinder binder = new KitchenTimerBinder();
	private String action = null;

	@Override
	public void onCreate() {
		super.onCreate();

		if (DEBUG) {
			Toast toast = Toast.makeText(getApplicationContext(), "onCreate()",
					Toast.LENGTH_SHORT);
			toast.show();
		}
	}

	private Runnable task = new Runnable() {
		public void run() {
			try {
				if (action.equals(ACTION_START)) {
					// 初期起動
				} else {
					// タイマー起動
					synchronized (binder) {
						try {
							execute();
						} catch (Exception e) {
							Debug.d(this, null, e);
						}
					}
				}

				setNextTime(NoteUpdatorService.this);
			} finally {
				NoteUpdatorService.this.stopSelf();
			}
		}

		private void execute() {
			if (!NetworkUtil
					.isConnected(NoteUpdatorService.this)){
				return;
			}
			
			Initialize.initialize(NoteUpdatorService.this);
			Initialize.initialize(NoteUpdatorService.this, "");
			
			int noteItemType = pref.getInt(Constant.PREF_NOTE_ITEM_TYPE,
					Constant.NOTE_ITEM_TYPE_ALL);
			String guid = pref.get(Constant.PREF_NOTE_ITEM_GUID);

			NoteUpdator updator = NoteUpdator.getInstance();
			updator.update(NoteUpdatorService.this, noteItemType, guid);
			
			Intent intent = new Intent(Constant.ACTION_UPDATE);
			sendBroadcast(intent);
		}
	};

	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);

		action = intent.getAction();
		action = (action == null) ? "" : action;

		if (DEBUG) {
			Toast toast = Toast.makeText(getApplicationContext(), "onStart() "
					+ action + " " + startId, Toast.LENGTH_SHORT);
			toast.show();
		}

		Thread thread = new Thread(null, task, "AlarmService_Service");
		thread.start();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();

		if (DEBUG) {
			Toast toast = Toast.makeText(getApplicationContext(),
					"onDestroy()", Toast.LENGTH_SHORT);
			toast.show();
		}
	}

	@Override
	public IBinder onBind(Intent intent) {
		if (DEBUG) {
			Toast toast = Toast.makeText(getApplicationContext(), "onBind()",
					Toast.LENGTH_SHORT);
			toast.show();
		}

		return binder;
	}

	@Override
	public void onRebind(Intent intent) {
		if (DEBUG) {
			Toast toast = Toast.makeText(getApplicationContext(), "onRebind()",
					Toast.LENGTH_SHORT);
			toast.show();
		}
	}

	@Override
	public boolean onUnbind(Intent intent) {
		if (DEBUG) {
			Toast toast = Toast.makeText(getApplicationContext(), "onUnbind()",
					Toast.LENGTH_SHORT);
			toast.show();
		}
		return true;
	}

	public static void setNextTime(Context context) {
		EditPrefUtil pref = new EditPrefUtil(context);

		long updateTime = pref.getLong(Constant.PREF_UPDATE_TIME);
		Calendar cal = Calendar.getInstance();
		cal.setTimeInMillis(updateTime);
		int h = cal.get(Calendar.HOUR_OF_DAY);
		int m = cal.get(Calendar.MINUTE);
		int s = cal.get(Calendar.SECOND);

		s = 0;
		long t = DateUtil.next(h, m, s, DS);
		PendingIntent alarmSender = PendingIntent.getService(context, 0,
				new Intent(context,
						NoteUpdatorService.class), 0);
		AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
		am.set(AlarmManager.RTC, t, alarmSender);
	}
	
	public static void stopService(Context context) {
		PendingIntent alarmSender = PendingIntent.getService(context, 0,
				new Intent(context, NoteUpdatorService.class),
				PendingIntent.FLAG_CANCEL_CURRENT);
	}

	public static boolean isSetAlarmSender(Context context) {
		PendingIntent alarmSender = PendingIntent.getService(context, 0,
				new Intent(context, NoteUpdatorService.class),
				PendingIntent.FLAG_NO_CREATE);
		return alarmSender != null;
	}
	
	public static void init(Context context){
		EditPrefUtil pref = new EditPrefUtil(context);

		boolean isSet = NoteUpdatorService.isSetAlarmSender(context);
		int autoUpdate = pref.getInt(Constant.PREF_AUTO_UPDATE);
		long updateTime = pref.getLong(Constant.PREF_UPDATE_TIME);
		
		if (autoUpdate != 0 && updateTime >= 0){
			if (!isSet){
				// 再起動時
				setNextTime(context);
			}
		}
		else {
			if (isSet){
				// データ削除時
				// isSetはクリアされないが、問題なので毎回よぶ
				stopService(context);
			}
		}
	}
}