package com.baidu.location.service;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.baidu.baidulocationdemo.R;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.Poi;
import com.baidu.location.demo.LocationActivity;
import com.baidu.location.demo.LocationApplication;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
/**
 * Created by admin on 2016/7/18.
 */
public class MyLocationService extends Service {
    private LocationService locationService;
    public static String workid;
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    @Override
    public void onCreate() {
        super.onCreate();
        Log.i("warn", "oncreate");
    }
    @Override
    public void onStart(Intent intent, int startid) {
        super.onStart(intent, startid);
// -----------location config ------------
        locationService = ((LocationApplication) getApplication()).locationService;
        //获取locationservice实例,建议应用中只初始化1个location实例,然后使用,可以参考其他示例的activity,都是通过此种方式获取locationservice实例的
        locationService.registerListener(mListener);
        //注册监听
        Log.i("warn", "onstart");
        int type = intent.getIntExtra("from", 0);
        if (type == 0) {
            locationService.setLocationOption(locationService.getDefaultLocationClientOption());
        } else if (type == 1) {
            locationService.setLocationOption(locationService.getOption());
        }
        MyLocationService.workid = intent.getStringExtra("workid");
        locationService.start();
    }
    @Override
    public void onDestroy() {
        Log.i("warn", "ondestroy");
        locationService.stop(); //停止定位服务
        locationService.unregisterListener(mListener); //注销掉监听
    }
    public BDLocationListener mListener = new BDLocationListener() {
        @Override
        public void onReceiveLocation(BDLocation location) {
            // TODO Auto-generated method stub
            if (null != location && location.getLocType() != BDLocation.TypeServerError) {
                final String longitude, latitude, jingdu, speed, city;
                //String time = location.getTime();
                Date date = new Date();
                final long timestamp = date.getTime();          //时间
                longitude = Double.toString(location.getLongitude());     //经度
                latitude = Double.toString(location.getLatitude());     //纬度
                jingdu = Float.toString(location.getRadius());       //精度
                city = location.getCity();
                speed = Float.toString(location.getSpeed());        //gps下运行速度
                final String workid = MyLocationService.workid;
                Log.i("workid", workid);
                new Thread() {
                    @Override
                    public void run() {
                        httpget(workid, timestamp, longitude, latitude, jingdu, city, speed);
                    }
                }.start();
            }
        }
    };
    public String httpget(String workid, long time, String longitude, String latitude, String jingdu, String city, String speed) {
        String result = "";
        BufferedReader in = null;
        StringBuilder buf = new StringBuilder("http://www.agribiotech.cn/record/record/sizerecord");
        buf.append("?");
        buf.append("workid=" + workid + "&");
        buf.append("timestamp=" + time + "&");
        buf.append("lng=" + longitude + "&");
        buf.append("lat=" + latitude + "&");
        buf.append("radius=" + jingdu + "&");
        buf.append("city=" + URLEncoder.encode(city) + "&");
        buf.append("speed=" + speed);
        try {
            URL url = null;
            url = new URL(buf.toString());
            URLConnection conn = url.openConnection();
            conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            conn.setRequestProperty("Accept", "application/json");
            conn.connect();
            Map<String, List<String>> map = conn.getHeaderFields();
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += "\n" + line;
            }
        } catch (IOException e) {
            Log.i("warn", e.toString());
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }
}