package com.usai.redant.raimage;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;

import com.usai.redant.redantmobile.RedAntApplication;
import com.usai.redant.util.RAUploadManager;
import com.usai.redant.util.dbgUtil;

import java.util.ArrayList;

//import com.usai.redant.util.RAUploadManager;
//import com.usai.redant.util.dbgUtil;

public class UploadService extends Service
{

//	private UploadThread	uploadThread;

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

    public RAUploadManager uploadManager = new RAUploadManager();

    // private boolean location_changed = false;

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        Log.d("", "onBind: bind service");
        return new MyBinder();
    }


    public class MyBinder extends Binder {
        /**
         * 获取当前Service的实例
         *
         * @return
         */
        public UploadService getService() {
            return UploadService.this;
        }
    }

    @Override
    public void onCreate() {

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


        // 初始化异常捕获器
        CrashHandler.getSharedInstance().init(getApplicationContext());
        CrashHandler.getSharedInstance().preserver = new CrashHandler.InfoPreserver() {
            @Override
            public void saveUserInformation() {
                if (uploadManager != null) {
                    uploadManager.saveTasks();
                }
            }

            @Override
            public void handleCrashInfo(String deviceInfo, String exception) {
                dbgUtil.fileLog("============================ app crash ============================");
                dbgUtil.fileLog("DEVICE");
                dbgUtil.fileLog(deviceInfo);
                dbgUtil.fileLog("EXCEPTION");
                dbgUtil.fileLog(exception);
                dbgUtil.fileLog("=============================== end ===============================");
                Log.d("_SERVICE", "Device Info: " + deviceInfo);
                Log.d("_SERVICE", "Crash Info: " + exception);
            }
        };

        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("REDANT.RAImage.ADD_TASK");
        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();

    }

    @Override
    public void onDestroy() {
        Log.e("_SERVICE", "onDestroy: ");
        uploadManager.saveTasks();
    }
//	void gps_off()
//	{
//		locationManager.removeUpdates(locationListener);
//	}
//
//	void gps_on()
//	{
//		if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
//		{
//
////            RedAntApplication.getInstance()
//
////            if(!RAUtil.checkPermission(this.getApplicationContext(),"android.permission.ACCESS_FINE_LOCATION"))
////                return;
//
//
//
//			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("RA Image", 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("RA Image", 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+" and try_count<3 ", 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 +" and try_count<3 ", 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 = AES.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 = AES.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 + ", try_count = try_count+1 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.RAImage.ADD_TASK".equals(action)) {

                ArrayList<Bundle> tasks = intent.getParcelableArrayListExtra("tasks");


                uploadManager.addTasks(tasks);
            } else if ("REDANT.RAImage.SAVE_TASK".equals(action)) {
                uploadManager.stopAllTasks();
            } 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;
                } else {
                    int iconntype = -1;
                    iconntype = networkInfo
                            .getType();
                    SharedPreferences pref = RedAntApplication
                            .getInstance()
                            .getSharedPreferences(
                                    "UploadManager",
                                    0);


                    boolean
                            wifi_only
                            = pref.getBoolean("wifi_only",
                            false);

                    if
                            (wifi_only
                            == true
                            && iconntype !=
                            ConnectivityManager.TYPE_WIFI
                            && iconntype !=
                            9/* earthnet */) {
                        uploadManager.stopAllTasks();
//															 dbgUtil.Log(Log.DEBUG,
//															 "Current Network info",
//															 "not allowed!Connection type="
//															 +
//															 networkInfo.getTypeName());
                        return;
                    }
                }


            }
        }
    };
}
