package com.oo.seex.sys_state;

import android.content.Context;

import com.oo.seex.sys_state.state.BatteryStateReceiver;
import com.oo.seex.sys_state.state.BluetoothStateReceiver;
import com.oo.seex.sys_state.state.TimeTickReceiver;
import com.oo.seex.sys_state.state.WifiStateReceiver;
import com.oo.seex.sys_state.state.bean.BaseState;

/**
 * Created by gyp on 17/7/4.
 */

public class SystemStateManager implements StateMamager,Register{
    private Context context;
    WifiStateReceiver wifiStateReceiver;
    BatteryStateReceiver batteryStateReceiver;
    BluetoothStateReceiver bluetoothStateReceiver;
    TimeTickReceiver timeTickReceiver;
    StateListener listener;
    int flag = 0;

    /**
     * 获取全部状态的构造方法
     * @param context
     */
    public SystemStateManager(Context context){
        this.context = context;
        flag = Config.FLAG_BLUETOOTH_STATE|Config.FLAG_BATTERY_STATE|Config.FLAG_TIME_STATE|Config.FLAG_WIFI_STATE;
    }

    /**
     * 可以有选择获取状态的构造方法
     * @param context
     * @param flag Config.FLAG_BLUETOOTH_STATE|Config.FLAG_BATTERY_STATE|Config.FLAG_TIME_STATE|Config.FLAG_WIFI_STATE
     */
    public SystemStateManager(Context context,int flag){
        this.context = context;
        this.flag = flag;
    }
    @Override
    public void registStateListener(StateListener listener) {
        this.listener = listener;
        regist();
    }

    @Override
    public void unRegiststateListener() {
        this.listener = null;
        unRegist();
    }

    @Override
    public void callback(int flag, BaseState state) {
        listener.onSysStateChange(flag, state);
    }

    /**
     * 注册系统事件
     */
    private void regist(){
        if((flag&Config.FLAG_WIFI_STATE) !=0){
            wifiStateReceiver = new WifiStateReceiver(context,this);
            wifiStateReceiver.regist();
        }

        if((flag&Config.FLAG_BATTERY_STATE) !=0){
            batteryStateReceiver = new BatteryStateReceiver(context,this);
            batteryStateReceiver.regist();
        }

        if((flag&Config.FLAG_BLUETOOTH_STATE) !=0){
            bluetoothStateReceiver = new BluetoothStateReceiver(context,this);
            bluetoothStateReceiver.regist();
        }

        if((flag&Config.FLAG_TIME_STATE) !=0){
            timeTickReceiver = new TimeTickReceiver(context,this);
            timeTickReceiver.regist();
        }

    }

    /**
     * 反注册系统事件
     */
    private void unRegist(){
        if(wifiStateReceiver != null){
            wifiStateReceiver.unRegist();
            wifiStateReceiver = null;
        }

        if(batteryStateReceiver != null){
            batteryStateReceiver.unRegist();
            batteryStateReceiver = null;
        }

        if(bluetoothStateReceiver != null){
            bluetoothStateReceiver.unRegist();
            bluetoothStateReceiver = null;
        }

        if(timeTickReceiver != null){
            timeTickReceiver.unRegist();
            timeTickReceiver = null;
        }

    }
}