package com.usai.apex;

import org.json.JSONException;
import org.json.JSONObject;

import com.usai.util.Crypto;
import com.usai.util.Network;
import com.usai.util.dbUtil;
import com.usai.util.dbgUtil;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Parcelable;
import android.os.SystemClock;
import android.util.Log;

public class Alarmreceiver extends BroadcastReceiver
{
	private SearchTask	m_task	= null;

	public void checkpush(Context context)
	{

		if (m_task != null)
		{
			return;
		}
		// mStatusMessageView.setText(R.string.str_Loading);
		// showProgress(true);
		m_task = new SearchTask(context);

		// TextView text_page = (TextView) view_page_footer
		// .findViewById(R.id.text_page);
		// text_page.setText("Loading...");
		// text_page.setEnabled(false);
		m_task.execute();

	}

	class SearchTask extends AsyncTask<Void, Void, Boolean>
	{
		int		errorcode;
		String	content	= null;
		Context	mcontext;

		public SearchTask(Context context)
		{
			mcontext = context;
		}

		@Override
		protected Boolean doInBackground(Void... params)
		{
			Log.d("SearchTask", "doInBackground");
			if (!Network.NetworkIsAvailable())

			{
				errorcode = Network.RESULT_NET_NOTAVAILABLE;
				return false;
			}
			String jstr = "";
			jstr = Network.check_push();
			// if (module_name.equals("Announcements"))
			// jstr = Network.get_announcements(lastid, limit);
			// else
			// jstr = Network.get_marketnews(lastid, limit);
			if (jstr == null || jstr.length() <= 0)
			{
				// Log.d(TAG, "json is wrong");

				errorcode = Network.RESULT_NET_ERROR;
				return false;
			}

			content = jstr;
			return true;
		}

		@Override
		protected void onPostExecute(Boolean success)
		{
			String tag = "onPostExecute@Alarmreceiver";
			Log.i( tag, "entry");
			m_task = null;
			// showProgress(false);

			// switch (errorcode)
			// {
			// // case Network.RESULT_NET_NOTAVAILABLE:
			// // {
			// // Toast toast = Toast.makeText(
			// // ApexTrackingApplication.get_instance(),
			// // getText(R.string.msg_connection_none),
			// // Toast.LENGTH_LONG);
			// // toast.setGravity(Gravity.CENTER, 0, 0);
			// // toast.show();
			// // break;
			// // }
			// // case Network.RESULT_NET_ERROR:
			// // {
			// // Toast toast = Toast.makeText(
			// // ApexTrackingApplication.get_instance(),
			// // getText(R.string.msg_net_error), Toast.LENGTH_LONG);
			// // toast.setGravity(Gravity.CENTER, 0, 0);
			// // toast.show();
			// // break;
			// // }
			// // case Network.RESULT_ERROR:
			// // // case Network.RESULT_RESPONSE_NULL:
			// // {
			// // Toast toast = Toast.makeText(
			// // ApexTrackingApplication.get_instance(),
			// // getText(R.string.msg_net_resulterror),
			// // Toast.LENGTH_LONG);
			// // toast.setGravity(Gravity.CENTER, 0, 0);
			// // toast.show();
			// // break;
			// // }
			//
			// default:
			// break;
			// }

			if (success)
			{
				JSONObject jsobj;
				//
				// array = new JSONArray(json);
				try
				{
					jsobj = new JSONObject(content);

					String message = jsobj.getString("message");
					String date = jsobj.getString("date");
					String s_id = jsobj.getString("s_id");
					String e_id = jsobj.getString("e_id");
					int count = jsobj.getInt("count");
					SQLiteDatabase db = dbUtil.OpenDB(
							ApexTrackingApplication.get_instance(), null, true);
					db.execSQL("insert into push_message(s_id,e_id,msgcount,message,h_time,user,create_time,read) values('"
							+ s_id
							+ "','"
							+ e_id
							+ "',"
							+ count
							+ ",'"
							+ message
							+ "','"
							+ date
							+ "','"
							+ ApexTrackingApplication.get_user()
							+ "',"
							+ System.currentTimeMillis() + ",0)");
					dbUtil.CloseDB(db);

					boolean bnotify = mcontext.getSharedPreferences("setting",
							0).getBoolean("notifications_new_message", true);
					if (bnotify)
					{

						boolean bsound = mcontext.getSharedPreferences(
								"setting", 0).getBoolean(
								"notifications_new_message_sound", true);
						boolean bvibrate = mcontext.getSharedPreferences(
								"setting", 0).getBoolean(
								"notifications_new_message_vibrate", true);
						NotificationManager nManager = (NotificationManager) mcontext
								.getSystemService(Context.NOTIFICATION_SERVICE);

						Notification notification = new Notification(
								R.drawable.ic_launcher,
								mcontext.getString(R.string.str_notification_title),
								System.currentTimeMillis());
						Intent intent = new Intent(mcontext,
								FunctionSelectActivity.class);
						intent.putExtra("launcher", "notification");

						PendingIntent pintent = PendingIntent.getActivity(
								mcontext, 0, intent,
								PendingIntent.FLAG_UPDATE_CURRENT);
						if (bsound && bvibrate)
							notification.defaults = Notification.DEFAULT_ALL;
						else if (bsound)
							notification.defaults = Notification.DEFAULT_SOUND
									| Notification.DEFAULT_LIGHTS;
						else if (bvibrate)
							notification.defaults = Notification.DEFAULT_VIBRATE
									| Notification.DEFAULT_LIGHTS;
						notification.flags = Notification.FLAG_AUTO_CANCEL;
						notification.number = ApexTrackingApplication.ncount++;
						if (notification.number > 1)
							notification
									.setLatestEventInfo(
											mcontext,
											notification.number
													+ " "
													+ ApexTrackingApplication
															.get_instance()
															.getString(
																	R.string.str_mnotification_title),
											ApexTrackingApplication
													.get_instance()
													.getString(
															R.string.str_notification_text)
													+ date, pintent);
						else
							notification
									.setLatestEventInfo(
											mcontext,
											ApexTrackingApplication
													.get_instance()
													.getString(
															R.string.str_notification_title),
											ApexTrackingApplication
													.get_instance()
													.getString(
															R.string.str_notification_text)
													+ date, pintent);
						nManager.notify(R.layout.activity_apex, notification);
					}

					// Intent intenticon = new Intent();
					// intenticon.setClass(ApexTrackingApplication
					// .get_instance(), FunctionSelectActivity.class);
					// Intent addShortcut = new
					// Intent("com.android.launcher.action.INSTALL_SHORTCUT");
					// Parcelable icon =
					// Intent.ShortcutIconResource.fromContext(mcontext,
					// R.drawable.ic_launcher_new);
					// addShortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME,
					// ApexTrackingApplication
					// .get_instance().getString(R.string.app_name));
					// addShortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT,
					// intent);
					// addShortcut.putExtra("duplicate", 0);
					// addShortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
					// icon);
					// ApexTrackingApplication
					// .get_instance().sendBroadcast(addShortcut);

					// notification

				}
				catch (JSONException e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				// if (bfinish)
				// {
				// // getListView().removeFooterView(view_page_footer);
				// // Toast.makeText(AnnouncementActivity.this, "Load all!",
				// // Toast.LENGTH_LONG).show();
				//
				// TextView tv = (TextView) view_page_footer
				// .findViewById(R.id.text_page);
				// tv.setText("No more items");
				// tv.setEnabled(false);
				// }
				// else
				// {
				// TextView tv = (TextView) view_page_footer
				// .findViewById(R.id.text_page);
				// tv.setText("More...");
				// tv.setEnabled(true);
				// }
				// adapter.notifyDataSetChanged();
				// // getListAdapter().notifyDataSetChanged;
				// // BaseAdapter mJson = null;
				// // mJson.notifyDataSetChanged();
			}

			super.onPostExecute(success);
		}

		@Override
		protected void onCancelled()
		{
			m_task = null;
			// showProgress(false);
		}
	}

	@Override
	public void onReceive(Context context, Intent intent)
	{
		String tag = "onReceive@Alarmreceiver";
		if (intent.getAction().equals("com.usai.apex.push"))
		{

			// Bundle b = intent.getExtras();
			// Set<String> keySet = b.keySet();
			// for(String key : keySet) {
			// Log.e(tag, key);
			// }
			// String s =b.getString("caller");
			Log.i( tag, "receive alarm broadcast caller =="
					+ intent.getStringExtra("caller"));

			if (SystemClock.elapsedRealtime()
					- ApexTrackingApplication.getLastCheckMessageTime() > 120000)
			{
				Log.i(tag, "check messsage");
				ApexTrackingApplication.UpdateLastCheckMessageTime();
				checkpush(context);

			}
			// Intent i = new Intent();
			// i.setClass(context, DaemonService.class);
			// // 启动service
			// // 多次调用startService并不会启动多个service 而是会多次调用onStart
			// context.startService(i);
		}
		else if (intent.getAction().equals("com.usai.apex.push.cancel"))
		{
			if (m_task != null)
				m_task.cancel(true);
			NotificationManager nManager = (NotificationManager) context
					.getSystemService(Context.NOTIFICATION_SERVICE);
			nManager.cancel(R.layout.activity_apex);
			ApexTrackingApplication.cancelalarm();
			// ApexTrackingApplication.put_password("");
			// ApexTrackingApplication.put_sessionid("");
			// ApexTrackingApplication.put_user("");
			ApexTrackingApplication.logout();

		}
	}

}
