package com.uiui.os.utils;

import android.content.Context;
import android.util.Log;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;

public class AmapManager {
    private static AmapManager sInstance;
    private Context mContext;
    public static AMapLocationClient locationClient = null;
    private String TAG = AmapManager.class.getSimpleName();

    private AmapManager(Context context) {
        this.mContext = context;
    }

    public static void init(Context context) {
        if (sInstance == null) {
            sInstance = new AmapManager(context);
        }

    }

    public static AmapManager getInstance() {
        if (sInstance == null) {
            throw new IllegalStateException("You must be init AmapManager first");
        }

        return sInstance;
    }

    public AMapLocationClient getLocationClient() {
        if (null == locationClient) {
            initAmap();
        }
        return locationClient;
    }

    public void initAmap() {
        locationClient = new AMapLocationClient(mContext);
        AMapLocationClientOption option = new AMapLocationClientOption();
        option.setLocationPurpose(AMapLocationClientOption.AMapLocationPurpose.SignIn);
        option.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        option.setNeedAddress(true);
        //获取一次定位结果：
        //该方法默认为false。
        option.setOnceLocation(true);
        //获取最近3s内精度最高的一次定位结果：
        //设置setOnceLocationLatest(boolean b)接口为true，启动定位时SDK会返回最近3s内精度最高的一次定位结果。
        // 如果设置其为true，setOnceLocation(boolean b)接口也会被设置为true，反之不会，默认为false。
        option.setOnceLocationLatest(true);
        locationClient.setLocationOption(option);
        //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
        //设置定位监听
        locationClient.setLocationListener(new AMapLocationListener() {

            @Override
            public void onLocationChanged(AMapLocation aMapLocation) {
                //errCode等于0代表定位成功，其他的为定位失败，具体的可以参照官网定位错误码说明
                if (aMapLocation.getErrorCode() == 0) {
                    Log.e(TAG, "onLocationChanged: " + "定位成功");
                    Log.e(TAG, "onLocationChanged: " + aMapLocation.getAddress());
                } else {
                    //定位失败
                    Log.e(TAG, "onLocationChanged: " + "定位失败");
                }
            }
        });
        //设置场景模式后最好调用一次stop，再调用start以保证场景模式生效
        locationClient.stopLocation();
        locationClient.startLocation();
        Log.e(TAG, "initAmap: " + "startLocation");
    }
}
