package com.usai.redant.photo;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

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

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.text.TextUtils;
import android.util.Log;
import android.widget.EditText;
import android.widget.RadioGroup;

public class UploadService extends Service
{

	private UploadThread	uploadThread;

	private boolean			queue_changed	= false;
	LocationManager			locationManager;
	LocationListener		locationListener;

	// private boolean location_changed = false;

	@Override
	public IBinder onBind(Intent intent)
	{
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onCreate()
	{

		Log.d("", "create upload Service!!!");
		if (uploadThread == null)
		{
			uploadThread = new UploadThread();
			Log.d("", "create upload thread!!!");
			// upleadThread.start();

		}

		IntentFilter msgFilter = new IntentFilter();

		msgFilter.addAction("REDANT.POP.MODIFY_QUEUE");
		msgFilter.addAction("REDANT.POP.GPS_ON");
		msgFilter.addAction("REDANT.POP.GPS_OFF");
		msgFilter.addAction("REDANT.POP.REQUEST_LOCATION");
		msgFilter.addAction("REDANT.POP.RESET_LOCATION");
		msgFilter.addAction("REDANT.POP.QUERY_UPLOAD_STATE");
		msgFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
		msgFilter.addAction("REDANT.POP.RETRY_UPLOAD");
		
		registerReceiver(uploadReceiver, msgFilter);
		// registerReceiver(uploadReceiver,
		// new IntentFilter("modify upload queue"));

		locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

		locationListener = new LocationListener()
		{

			// Provider的状态在可用、暂时不可用和无服务三个状态直接切换时触发此函数
			@Override
			public void onStatusChanged(String provider, int status,
					Bundle extras)
			{

			}

			// Provider被enable时触发此函数，比如GPS被打开
			@Override
			public void onProviderEnabled(String provider)
			{

			}

			// Provider被disable时触发此函数，比如GPS被关闭
			@Override
			public void onProviderDisabled(String provider)
			{

			}

			// 当坐标改变时触发此函数，如果Provider传进相同的坐标，它就不会被触发
			@Override
			public void onLocationChanged(Location location)
			{
				// if (location != null)
				// {
				// location_changed = true;
				// Log.d("Map",
				// "Location changed : Lat: " + location.getLatitude()
				// + " Lng: " + location.getLongitude());
				// }
			}
		};

		super.onCreate();

	}

	void gps_off()
	{
		locationManager.removeUpdates(locationListener);
	}

	void gps_on()
	{
		if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
		{

			locationManager.requestLocationUpdates(
					LocationManager.GPS_PROVIDER, 60 * 1000, 50,
					locationListener);

		}
		else if (locationManager
				.isProviderEnabled(LocationManager.NETWORK_PROVIDER))
		{

			locationManager.requestLocationUpdates(
					LocationManager.NETWORK_PROVIDER, 30 * 1000, 50,
					locationListener);

		}
	}

	void update_location()
	{

		Location location = null;
		if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
		{

			location = locationManager
					.getLastKnownLocation(LocationManager.GPS_PROVIDER);

		}
		else if (locationManager
				.isProviderEnabled(LocationManager.NETWORK_PROVIDER))
		{

			location = locationManager
					.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

		}

		SharedPreferences pref = RedAntApplication.getInstance()
				.getSharedPreferences("POP", 0);

		SharedPreferences.Editor editor = pref.edit();
		if (location != null)
		{

			editor.putFloat("Lat", (float) location.getLatitude());
			editor.putFloat("Lon", (float) location.getLongitude());

		}
		editor.commit();

	}

	void check_location()
	{

		Location location = null;
		if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
		{

			location = locationManager
					.getLastKnownLocation(LocationManager.GPS_PROVIDER);

		}
		else if (locationManager
				.isProviderEnabled(LocationManager.NETWORK_PROVIDER))
		{

			location = locationManager
					.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

		}

		SharedPreferences pref = RedAntApplication.getInstance()
				.getSharedPreferences("POP", 0);
		double lat = pref.getFloat("Lat", 9999);
		double lon = pref.getFloat("Lon", 9999);

		// SharedPreferences.Editor editor = pref.edit();
		if (location != null)
		{
			float[] result = new float[1];
			if (lat != 9999 && lon != 9999)
			{
				Location.distanceBetween(lat, lon, location.getLatitude(),
						location.getLongitude(), result);
				if (result[0] > 1000)
				{
					sendBroadcast(new Intent("REDANT.POP.STATION_CHANGE"));
					return;
				}
				else
				{
					sendBroadcast(new Intent("REDANT.POP.STATION_NOT_CHANGE"));
					return;
				}
			}
			sendBroadcast(new Intent("REDANT.POP.STATION_NOT_CHANGE"));
			return;
			// new Location();
			//
			// Location.distanceBetween(lat, lon, endLatitude, endLongitude,
			// results)
			//
			// editor.putFloat("Lat", (float) location.getLatitude());
			// editor.putFloat("Lon", (float) location.getLongitude());

		}
		else
		{
			sendBroadcast(new Intent("REDANT.POP.STATION_NOT_CHANGE"));
			return;
		}
		// editor.commit();

		// Log.d("location:", "lat:" + latitude + "lon:" + longitude);
	}

	// void loadlist()
	// {
	//
	// }

	public class UploadThread extends Thread
	{
		@Override
		public void run()
		{

			Log.d("", "upload thread running");

			super.run();
			doupload();
			Log.d("", "upload thread stop");

		}

		private void doupload()
		{
			boolean error = false;
			boolean didupload = false;
			// int verifyresult = Network.VerifyUser(RedAntApplication.user,
			// RedAntApplication.password);
			// if (verifyresult == Network.RESULT_TRUE)
			// {
			SQLiteDatabase dbr = dbUtil.OpenDB(UploadService.this, null, false);
			Cursor cursor = dbr.query("pics", new String[] { "_id", "pid",
					"local_path", "picker", "server" }, "err_code!="
					+ Network.AP_UPLOAD_SUCCESS+" and err_code!="+ Network.RESULT_LOCALFILE_ERROR, null, null, null, "_id", null);
			while (cursor.moveToNext())
			{
				didupload = true;
				if (queue_changed)
				{
					queue_changed = false;
					dbUtil.CloseCursor(cursor);
					cursor = dbr.query("pics", new String[] { "_id", "pid",
							"local_path", "picker", "server" }, "err_code!="
							+ Network.AP_UPLOAD_SUCCESS+" and err_code!="+ Network.RESULT_LOCALFILE_ERROR, null, null, null,
							"_id", null);
					if (!cursor.moveToNext())
						break;

				}
				int _id = cursor.getInt(0);
				String pid = cursor.getString(1);
				String path = cursor.getString(2);
				String picker = cursor.getString(3);
				String server = cursor.getString(4);

				String encryptUser = "";

				try
				{
					encryptUser = Crypto.encrypt("apexu", picker);

				}
				catch (Exception e1)
				{
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}

				Cursor cursor_user = dbr.query("users",
						new String[] { "pass" }, "name='" + encryptUser + "'",
						null, null, null, "_id", null);
				String pass = "";
				if (cursor_user.moveToNext())
					pass = cursor_user.getString(0);
				try
				{
					pass = Crypto.decrypt("apexp", pass);
				}
				catch (Exception e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				int uploadresult = Network.UploadImage(path, picker, pass, pid,
						server);
				if (uploadresult == Network.RESULT_TRUE)
				{
				
					RedAntApplication.writeLock.lock();

					// write sql process
					SQLiteDatabase dbw = dbUtil.OpenDB(UploadService.this,
							null, true);
					// String sql = "update pics set err_code ="
					// + Network.AP_UPLOAD_SUCCESS + " where _id="
					// + _id;
					String sql = "delete from pics  where _id=" + _id;
					dbw.execSQL(sql);

					String timeStamp = new SimpleDateFormat("yyyy_MM_dd")
							.format(new Date());

					File storageDir = new File(Environment
							.getExternalStorageDirectory().getPath()
							+ "/redant/pop/done/" + timeStamp);

					if (!storageDir.exists())
						storageDir.mkdirs();

					File pic = new File(path);
					// pic.delete();

					dbUtil.CloseDB(dbw);
					RedAntApplication.writeLock.unlock();
					dbgUtil.fileLog("upload success move file "
							+ pic.getName()
							+ " to "
							+ Environment.getExternalStorageDirectory()
									.getPath() + "/redant/pop/done/"
							+ timeStamp + File.separator);
					pic.renameTo(new File(Environment
							.getExternalStorageDirectory().getPath()
							+ "/redant/pop/done/"
							+ timeStamp
							+ File.separator
							+ pic.getName()));
					

				}
				else
				{
					error = true;
					RedAntApplication.writeLock.lock();

					{
						// write sql process
						SQLiteDatabase dbw = dbUtil.OpenDB(UploadService.this,
								null, true);
						String sql = "update pics set err_code ="
								+ uploadresult + " where _id=" + _id;

						dbw.execSQL(sql);
						dbUtil.CloseDB(dbw);
					}
					RedAntApplication.writeLock.unlock();
					dbgUtil.fileLog("upload failed pid:" + pid + " file:"
							+ path + " server:" + server + " err_code:"
							+ uploadresult);
					
				}

				sendBroadcast(new Intent("REDANT.POP.UPDATE_QUEUE_VIEW"));
			}

			dbUtil.CloseCursor(cursor);
			dbUtil.CloseDB(dbr);

			// }
			// else
			// {
			// Log.d("upload thread", "user check failed!");
			//
			// sendBroadcast(new Intent("REDANT.POP.USER_CHECK_FAILED"));
			// }

			if (queue_changed)
			{
				queue_changed = false;
				doupload();
			}
			if (didupload)
			{
				if (error)
				{
					sendBroadcast(new Intent(
							"REDANT.POP.FINISH_UPLOAD_QUEUE_WITH_ERROR"));
					RedAntApplication.startalarm();
				}
				else
				{
					sendBroadcast(new Intent("REDANT.POP.FINISH_UPLOAD_QUEUE"));
					RedAntApplication.cancelalarm();
				}
			}
		}
	}

	private BroadcastReceiver	uploadReceiver	= new BroadcastReceiver()
												{

													public void onReceive(
															Context context,
															Intent intent)
													{
														String action = intent
																.getAction();
														// 如果捕捉到的action是ACTION_BATTERY_CHANGED

														if ("REDANT.POP.REQUEST_LOCATION"
																.equals(action))
														{
															check_location();
															// if
															// (location_changed)
															// sendBroadcast(new
															// Intent(
															// "REDANT.POP.CHANGE_STATION"));

														}
														else if ("REDANT.POP.RETRY_UPLOAD"
																.equals(action))
														{
															if (uploadThread != null)
															{
																if (uploadThread
																		.isAlive())
																{

																	Log.d("uploadReceiver",
																			"upload thread alive");
																}
																else
																{
																	Log.d("uploadReceiver",
																			"start upload thread");
																	uploadThread = new UploadThread();
																	uploadThread
																			.start();
																}
															}
														}
														else if ("REDANT.POP.GPS_ON"
																.equals(action))
														{
															gps_on();
														}
														else if ("REDANT.POP.GPS_OFF"
																.equals(action))
														{

															gps_off();
														}
														else if ("REDANT.POP.RESET_LOCATION"
																.equals(action))
														{
															update_location();
															// location_changed
															// = false;
														}
														else if ("REDANT.POP.MODIFY_QUEUE"
																.equals(action))
														{
															Log.d("uploadservice",
																	"recieve upload queue change");
															// update_location();
															if (uploadThread != null)
															{
																if (uploadThread
																		.isAlive())
																{

																	Log.d("uploadReceiver",
																			"upload thread alive");
																}
																else
																{
																	Log.d("uploadReceiver",
																			"start upload thread");
																	uploadThread = new UploadThread();
																	uploadThread
																			.start();
																}
															}
														}
														else if ("REDANT.POP.QUERY_UPLOAD_STATE"
																.equals(action))
														{
															if (uploadThread
																	.isAlive())
															{
																sendBroadcast(new Intent(
																		"REDANT.POP.UPLOAD_STATE_TRUE"));
															}
															else
															{
																sendBroadcast(new Intent(
																		"REDANT.POP.UPLOAD_STATE_FALSE"));
															}
														}
														else if (intent
																.getAction()
																.equals(ConnectivityManager.CONNECTIVITY_ACTION))
														{

															ConnectivityManager connManager = (ConnectivityManager) context
																	.getSystemService(Context.CONNECTIVITY_SERVICE);

															NetworkInfo networkInfo = connManager
																	.getActiveNetworkInfo();
															if (networkInfo == null)
															{
																dbgUtil.Logd(
																		"Current Network info",
																		"can not get Active NetworkInfo!");
																return;
															}
															NetworkInfo.State netState = networkInfo
																	.getState();
															if (netState != NetworkInfo.State.CONNECTED)
															{
																dbgUtil.Logd(
																		"Current Network info",
																		"not Connected!State="
																				+ netState);
																return;
															}
															int iconntype = -1;
															iconntype = networkInfo
																	.getType();
															SharedPreferences pref = RedAntApplication
																	.getInstance()
																	.getSharedPreferences(
																			"POP",
																			0);

															String aa = pref
																	.getString(
																			"aa",
																			null);
															String ea = pref
																	.getString(
																			"ea",
																			null);
															if (iconntype == ConnectivityManager.TYPE_WIFI)
															{
																if (!TextUtils
																		.isEmpty(aa))
																	RedAntApplication.active_address = aa;
															}
															else
															{
																if (!TextUtils
																		.isEmpty(ea))
																	RedAntApplication.active_address = ea;
															}
															// boolean
															// bUseMobileNetwork
															// =
															// context.getSharedPreferences(
															// "PhoneAsstPref",
															// 0).getBoolean("UseMobileNetwork",
															// false);
															//
															// if
															// (bUseMobileNetwork
															// == false
															// && iconntype !=
															// ConnectivityManager.TYPE_WIFI
															// && iconntype !=
															// 9/* earthnet */)
															// {
															// dbgUtil.Log(Log.DEBUG,
															// "Current Network info",
															// "not allowed!Connection type="
															// +
															// networkInfo.getTypeName());
															// return false;
															// }
															boolean bavailable = networkInfo
																	.isAvailable();
															String strtype = networkInfo
																	.getTypeName();

															dbgUtil.Logd(
																	"Current Network info",
																	" type = "
																			+ strtype
																			+ " abailable = "
																			+ bavailable
																			+ " state "
																			+ netState);
															if (bavailable)
															{
																if (uploadThread
																		.isAlive())
																{

																	Log.d("uploadReceiver",
																			"upload thread alive");
																}
																else
																{
																	Log.d("uploadReceiver",
																			"start upload thread");
																	uploadThread = new UploadThread();
																	uploadThread
																			.start();
																}
															}

														}
													}
												};
}
