package com.ruiwenliu.wrapper.util;

import android.content.Context;
import android.database.ContentObserver;
import android.location.LocationManager;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;

public class GpsManager {

    private static GpsManager instance;
    private LocationManager locationManager;
    private Context mContext;

    private GpsManager(Context context) {
        mContext = context.getApplicationContext();
        locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
    }

    public static GpsManager getInstance(Context context) {
        if (instance == null) {
            instance = new GpsManager(context);
        }
        return instance;
    }

    private final ContentObserver observer = new ContentObserver(null) {
        @Override
        public void onChange(boolean selfChange) {
            boolean enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
            Log.e("xxxxxxxxxxxxxxxxxxxx", "selfChange = " + enabled);
            if (enabled) {
                gpsChangeHandler.sendEmptyMessage(0);
            } else {
                gpsChangeHandler.sendEmptyMessage(1);
            }
        }
    };

    private Handler gpsChangeHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    notifyGpsChange(true);
                    break;
                case 1:
                    notifyGpsChange(false);
                    break;
                default:
                    break;
            }
        }
    };

    /*****
     * 注册gps开关监听
     */
    public void rigister() {
        mContext.getContentResolver().registerContentObserver(Settings.Secure.getUriFor(Settings.Secure.LOCATION_PROVIDERS_ALLOWED), false, observer);
    }

    /*****
     * 注销gps开关监听
     */
    public void unRigister() {
        mContext.getContentResolver().unregisterContentObserver(observer);
    }

    private List<GpsChangeListener> listeners = new ArrayList<>();

    public void bindGpsListener(GpsChangeListener listener) {
        listeners.add(listener);
    }

    public void unbindGpsListener(GpsChangeListener listener) {
        if (listeners.contains(listener)) {
            listeners.remove(listener);
        }
    }

    private void notifyGpsChange(boolean b) {
        for (GpsChangeListener listener : listeners) {
            listener.gpsChange(b);
        }
    }

    /******
     * GPS 改变监听事件
     */
    public interface GpsChangeListener {
        void gpsChange(boolean b);
    }
}
