package ai.pai.client.services;

import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.android.common.executors.ThreadExecutor;
import com.android.common.utils.LogHelper;

import java.util.HashMap;

import ai.pai.client.BuildConfig;
import ai.pai.client.db.Preferences;
import ai.pai.client.utils.HttpPostTask;
import ai.pai.client.utils.UrlContainer;


public class MyLocationService extends Service {

    private AMapLocationClient locationClient = null;
    private AMapLocationClientOption locationOption = new AMapLocationClientOption();

    public static final int COMMAND_START_LOCATION = 9801;
    public static final int COMMAND_STOP_LOCATION = 9802;
    public static final int COMMAND_DESTROY_LOCATION = 9803;

    private double lastLat;
    private double lastLon;
    private double repeatTime;

    private int status = 0; // 0:未开始  1：已开始 2：已暂停

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

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if(intent==null){
            return super.onStartCommand(intent,flags,startId);
        }
        Bundle bundle= intent.getExtras();
        if(bundle==null){
            return super.onStartCommand(intent, flags, startId);
        }
        int command = bundle.getInt("command",0);
        initLocation();
        switch (command) {
            case COMMAND_START_LOCATION:
                startLocation();
                break;
            case COMMAND_STOP_LOCATION:
                stopLocation();
                break;
            case COMMAND_DESTROY_LOCATION:
                destroyLocation();
                break;
        }
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        destroyLocation();
    }

    /**
     * 初始化定位
     *
     * @since 2.8.0
     * @author hongming.wang
     *
     */
    private void initLocation(){
        if(locationClient!=null){
            return;
        }
        //初始化client
        locationClient = new AMapLocationClient(this.getApplicationContext());
        //设置定位参数
        locationClient.setLocationOption(getDefaultOption());
        // 设置定位监听
        locationClient.setLocationListener(locationListener);
        status = 0;
    }

    /**
     * 默认的定位参数
     * @since 2.8.0
     * @author hongming.wang
     *
     */
    private AMapLocationClientOption getDefaultOption(){
        AMapLocationClientOption mOption = new AMapLocationClientOption();
        mOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);//可选，设置定位模式，可选的模式有高精度、仅设备、仅网络。默认为高精度模式
        mOption.setGpsFirst(false);//可选，设置是否gps优先，只在高精度模式下有效。默认关闭
        mOption.setHttpTimeOut(30000);//可选，设置网络请求超时时间。默认为30秒。在仅设备模式下无效
        mOption.setInterval(30*1000);//可选，设置定位间隔。默认为30秒
        mOption.setNeedAddress(false);//可选，设置是否返回逆地理地址信息。默认是true
        mOption.setOnceLocation(false);//可选，设置是否单次定位。默认是false
        mOption.setOnceLocationLatest(false);//可选，设置是否等待wifi刷新，默认为false.如果设置为true,会自动变为单次定位，持续定位时不要使用
        AMapLocationClientOption.setLocationProtocol(AMapLocationClientOption.AMapLocationProtocol.HTTP);//可选， 设置网络请求的协议。可选HTTP或者HTTPS。默认为HTTP
        mOption.setSensorEnable(false);//可选，设置是否使用传感器。默认是false
        mOption.setWifiScan(true); //可选，设置是否开启wifi扫描。默认为true，如果设置为false会同时停止主动刷新，停止以后完全依赖于系统刷新，定位位置可能存在误差
        return mOption;
    }

    /**
     * 定位监听
     */
    AMapLocationListener locationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation loc) {
            double lat = loc.getLatitude();
            double lon = loc.getLongitude();
            reportLocationWhenTourMode(lat,lon);
        }
    };


    /**
     * 开始定位
     *
     * @since 2.8.0
     * @author hongming.wang
     *
     */
    private void startLocation(){
        if(status==1){
            return;
        }
        // 设置定位参数
        locationClient.setLocationOption(locationOption);
        // 启动定位
        locationClient.startLocation();

        status = 1;
    }

    /**
     * 停止定位
     *
     * @since 2.8.0
     * @author hongming.wang
     *
     */
    private void stopLocation(){
        if(status == 2){
            return;
        }
        // 停止定位
        locationClient.stopLocation();
        status = 2;
    }

    /**
     * 销毁定位
     *
     * @since 2.8.0
     * @author hongming.wang
     *
     */
    private void destroyLocation(){
        if (null != locationClient) {
            locationClient.onDestroy();
            locationClient = null;
            locationOption = null;
            status = 0;
        }
    }

private void reportLocationWhenTourMode(double lat, double lon){
    if(lat == lastLat && lon ==lastLon && repeatTime<5){
        repeatTime++;
        return;
    }
    repeatTime = 0;
    lastLat = lat;
    lastLon = lon;
    if(Preferences.getInstance(this).isTourMode()|| BuildConfig.DEBUG){
        HashMap<String,String> params = new HashMap<String,String>();
        String userId = Preferences.getInstance(this).getUserId();
        if(userId.length()==0){
            return;
        }
        params.put("user_id",userId);
        params.put("lon",String.valueOf(lon));
        params.put("lat",String.valueOf(lat));
        new HttpPostTask(this,params).executeOnExecutor(ThreadExecutor.getInstance().getExecutor(), UrlContainer.GEO_LOCATION_URL);
        LogHelper.d("czy","reportLocationWhenTourMode lat = "+lat+"lon="+lon);
    }
}

}
