package com.example.mountaintravel.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.example.mountaintravel.variable.Variable;
import com.google.code.microlog4android.Logger;
import com.google.code.microlog4android.LoggerFactory;
import com.google.code.microlog4android.config.PropertyConfigurator;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;

public class MyGPSservice extends Service {
	private static final Logger logger = LoggerFactory
			.getLogger(MyGPSservice.class);
	Location loca;
	SharedPreferences sp;
	String userID;

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	public void onCreate() {
		PropertyConfigurator.getConfigurator(this).configure();
		Log.d("TAG", "GPSService Start!");
		MyLocationListener LocationListener = new MyLocationListener();
		String serviceString = Context.LOCATION_SERVICE;
		// 获取的是位置服务
		LocationManager locationManager = (LocationManager) getSystemService(serviceString);
		final List<String> providers = locationManager.getProviders(true);
		for (String provider : providers) {
			locationManager.requestLocationUpdates(provider, 1000, 1,
					LocationListener);// 产生位置改变事件的条件设定为距离改变1m，时间1s
		}
		sp = getSharedPreferences("variable", Context.MODE_PRIVATE);
		userID = sp.getString("userid", null);
		// Log.d("TAG", "userID="+userID);
	}
	private Thread thread;
	// 获取位置
	private class MyLocationListener implements LocationListener {
		public void onLocationChanged(Location location) {
			 System.out.println("service 经度："+location.getLongitude()+"\t 纬度："+location.getLatitude());
			logger.debug("service 经度：" + location.getLongitude() + "\t 纬度："
					+ location.getLatitude());
			if (count == 0) {
				thread = new Thread(new MyThread());
				thread.start();
			}
			if (location != null) {
				loca = location;
				/*
				 * sp.edit().putString("location_x",
				 * location.getLongitude()+"").commit();
				 * sp.edit().putString("location_y",
				 * location.getLatitude()+"").commit();
				 */
			}
		}
		public void onProviderDisabled(String provider) {
		
		}

		public void onProviderEnabled(String provider) {
		}

		public void onStatusChanged(String provider, int status, Bundle extras) {
		}
	}

	int count;

	public class MyThread implements Runnable { // thread
		public void run() {
			if (count == 0) {
				String x = loca.getLongitude() + "";
				String y = loca.getLatitude() + "";
				Variable.myPointX = x;
				Variable.myPointY = y;
			}
			while (count < 20) {
				try {
					Thread.sleep(1000); // sleep 1000ms
					count++;
				} catch (Exception e) {
				}
			}
			if (count >= 20) {
				count = 0;
				// x= 120.218636746;
				// y = 30.3838916390001;
				uploadgps();
			}
		}
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		Log.d("TAG", "MyGPS onDestroy+");
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		return super.onStartCommand(intent, flags, startId);
	}

	/**
	 * 上传GPS
	 * 
	 * @param userName
	 * @param userPass
	 */
	// double x= 120.218636746;
	// double y = 30.3838916390001;
	private void uploadgps() {
		String x = loca.getLongitude() + "";
		String y = loca.getLatitude() + "";
		Variable.myPointX = x;
		Variable.myPointY = y;
		DefaultHttpClient client = new DefaultHttpClient();
		String uri = "http://" + Variable.address
				+ "/terminal/upload/eventUserXyzLog";
		HttpPost httpPost = new HttpPost(uri);
		try {
			List<NameValuePair> parameters = new ArrayList<NameValuePair>();
			// 往这个集合中添加你要传递的参数
			parameters.add(new BasicNameValuePair("user_id", userID));
			parameters.add(new BasicNameValuePair("user_name", sp.getString(
					"real_name", "")));
			parameters.add(new BasicNameValuePair("axis_x", x));
			parameters.add(new BasicNameValuePair("axis_y", y));
			// x=x+0.01;
			// y=y+0.01;
			// 创建传递参数封装 实体对象
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters,
					"UTF-8");// 设置传递参数的编码
			// 把实体对象存入到httpPost对象中
			httpPost.setEntity(entity);
			// 3. 调用第一步中创建好的实例的 execute 方法来执行第二步中创建好的 method 实例
			HttpResponse response = client.execute(httpPost); // HttpUriRequest的后代对象
			if (response.getStatusLine().getStatusCode() == 200) {
				String result = EntityUtils.toString(response.getEntity(),
						"UTF-8");
				// Log.d("TAG", "result=:"+result);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// 6. 释放连接。无论执行方法是否成功，都必须释放连接
			client.getConnectionManager().shutdown();
		}

	}

	/**
	 * 检测网络是否连接
	 * 
	 * @return
	 * */
	private boolean isNetworkAvailable() {
		// 得到网络连接信息
		ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		// 去进行判断网络是否连接
		if (manager.getActiveNetworkInfo() != null) {
			Log.e("TAG", "isNetworkAvailable=:"
					+ manager.getActiveNetworkInfo().isAvailable());
			return manager.getActiveNetworkInfo().isAvailable();
		}
		return false;
	}

	/**
	 * @category 判断是否有外网连接（普通方法不能判断外网的网络是否连接，比如连接上局域网）
	 * @return
	 */
	public static final boolean ping() {
		String result = null;
		try {
			String ip = "www.baidu.com";// ping 的地址，可以换成任何一种可靠的外网
			Process p = Runtime.getRuntime().exec("ping -c 3 -w 100 " + ip);// ping网址3次
			// 读取ping的内容，可以不加
			InputStream input = p.getInputStream();
			BufferedReader in = new BufferedReader(new InputStreamReader(input));
			StringBuffer stringBuffer = new StringBuffer();
			String content = "";
			while ((content = in.readLine()) != null) {
				stringBuffer.append(content);
			}
			Log.d("------ping-----",
					"result content : " + stringBuffer.toString());
			// ping的状态
			int status = p.waitFor();
			if (status == 0) {
				result = "success";
				return true;
			} else {
				result = "failed";
			}
		} catch (IOException e) {
			result = "IOException";
		} catch (InterruptedException e) {
			result = "InterruptedException";
		} finally {
			Log.d("----result---", "result = " + result);
		}
		return false;
	}
}
