package com.device.comm.mylibrary;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * Created by lvwang2002 on 16/1/28.
 */
public class BTClassicDeviceManager {
    private String TAG = "BT_CLASSIC_DEVICE_MANAGER";
    private static final String SPP_UUID = "00001101-0000-1000-8000-00805F9B34FB";// 蓝牙服务器的标识

    private BluetoothAdapter mBluetoothAdapter;
    private BleDeviceManager mDeviceManager;
    private Context mContext;
    private String supportDeviceName  = "RBP";
    private boolean mIsScan = false;
    private final HashMap<String, BTClassicDevice> m_map = new HashMap<String, BTClassicDevice>();
    private final ArrayList<BTClassicDevice> m_list = new ArrayList<BTClassicDevice>();

    private P_DeviceManager m_deviceMngr;


    public BTClassicDeviceManager(BluetoothAdapter bluetoothAdapter,
                                  BleDeviceManager deviceManager,
                                  Context context){

        mBluetoothAdapter = bluetoothAdapter;
        mDeviceManager = deviceManager;
        mContext = context;

        // Register the BroadcastReceiver
        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothDevice.ACTION_FOUND);
        filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
//        mContext.registerReceiver(mReceiver, filter);
    }


    public class DiscoverEvent{
        private BTClassicDevice mDevice;
        private boolean mNewlyDiscovered;

        public DiscoverEvent(BTClassicDevice device,boolean newlyDiscovered){
            mDevice = device;
            mNewlyDiscovered = newlyDiscovered;
        }

        public BTClassicDevice getDevice() {
            return mDevice;
        }

        public boolean isNewlyDiscovered() {
            return mNewlyDiscovered;
        }

    }

    /** 对外输入接口  */
    public interface BTClassicDiscoverListener{
        public void onDiscover(DiscoverEvent e);
        public void onStopDiscover();
        public void onBound(DiscoverEvent e);
    }

    BTClassicDiscoverListener mDiscoverListener = null;


    public void stopScan(){
        mIsScan = false;
        if (postNeeded()){
            post(new Runnable() {
                @Override
                public void run() {
                    mBluetoothAdapter.cancelDiscovery();
                }
            });
        }else{
            mBluetoothAdapter.cancelDiscovery();
        }
    }

    private BTClassicDeviceManager selfDeviceManager = this;
    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {


            if (intent == null) {
                Log.d(TAG,"异常");

                return;
            }

            String action = intent.getAction();

            Log.i(TAG,"接收到血压计 消息:"+ action);

            if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                Log.d(TAG, "经典蓝牙扫描被停止");
                if(mDiscoverListener == null){
                    return;
                }
                mDiscoverListener.onStopDiscover();
                return;
            }


            BluetoothDevice nativeDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            Log.d(TAG,"Native mac:"+nativeDevice.getAddress());
            Log.d(TAG,"bond:"+nativeDevice.getBondState());
            if(nativeDevice == null) {
                Log.d(TAG,"异常");

                return;
            }

            String name = nativeDevice.getName();
            if (stringIsEmpty(name)) {
                Log.d(TAG,"异常");

                return;
            }

            if(!name.startsWith(supportDeviceName)){
                Log.d(TAG,"扫描到非支持设备");

                return;
            }

//            mDiscoverListener.onEvent(event);

            // When discovery finds a device
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                if(!mIsScan){
                    Log.d(TAG,"已经关闭扫描");

                    return;
                }
                // Get the BluetoothDevice object from the Intent
                final String macAddress = nativeDevice.getAddress();
                BTClassicDevice device_sweetblue = getDevice(macAddress);

                boolean isNewlyDiscovered = false;
                DiscoverEvent discoverEvent;
                if ( device_sweetblue == null ) {
                    Log.d(TAG,"Discovered device " + name + " " + macAddress + " not in list.");
                    BTClassicDevice device = new BTClassicDevice(mBluetoothAdapter,selfDeviceManager,nativeDevice);
                    //尝试去绑定连接
//                    device.tryConnect();
                    add(device);
                    isNewlyDiscovered = true;
                    discoverEvent = new DiscoverEvent(device,isNewlyDiscovered);

                } else {
                    if( device_sweetblue.getBluetoothDevice().equals(nativeDevice) ) {
                        Log.d(TAG,"Discovered device " + name + " " + macAddress + " already in list.");
                    } else {
                        Log.e(TAG, "Discovered device " + name + " " + macAddress + " already in list but with new native device instance.");
                    }

                    isNewlyDiscovered = false;
                    discoverEvent = new DiscoverEvent(device_sweetblue,isNewlyDiscovered);
                }


                mDiscoverListener.onDiscover(discoverEvent);
            }else if(BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)){
                Log.d(TAG,"Native mac:"+nativeDevice.getAddress());
                BTClassicDevice btDevice =  getDevice(nativeDevice.getAddress());
                if(btDevice == null){
                    Log.d(TAG,"没有找到可以连接的设备");
                    return;
                }

                btDevice.actionBondStateChanged();

            }else if(BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)){
                final String macAddress = nativeDevice.getAddress();
                BTClassicDevice device_sweetblue = getDevice(macAddress);

                if(device_sweetblue != null){
                    Log.d(TAG,"接收到 ACTION_ACL_DISCONNECTED");
                    device_sweetblue.disconnect();
                }
            }
        }
    };

    /** 开始扫描普通蓝牙,打开扫描以前关闭低功耗蓝牙扫描 */
    public void startDiscover(final BTClassicDiscoverListener discoverListener){
        Log.d(TAG,"开始扫描经典蓝牙");
        mDiscoverListener = discoverListener;

        mDeviceManager.disableBleScan();
        if(postNeeded()){
            post(new Runnable() {
                @Override
                public void run() {
                    startScanBT();
                }
            });
        }else{
            startScanBT();
        }
    }

    private void startScanBT(){
        mIsScan = true;
        if(!mBluetoothAdapter.startDiscovery()){
            Log.d(TAG,"开始经典蓝牙扫描失败");
            return;
        }

        Log.d(TAG,"开始经典蓝牙扫描成功");
    }



    private boolean postNeeded() {
        return mDeviceManager.getUpdateLoop().postNeeded();
    }

    private void post(final Runnable runnable) {
        final UpdateLoop updateLoop = mDeviceManager.getUpdateLoop();

        updateLoop.postIfNeeded(runnable);
    }

    private boolean postMainThreadNeeded() {
        return mDeviceManager.getMainUpdateLoop().postNeeded();
    }

    private void postMainThread(final Runnable runnable) {
        final UpdateLoop updateLoop = mDeviceManager.getMainUpdateLoop();

        updateLoop.postIfNeeded(runnable);
    }

    public UpdateLoop getUpdateLoop(){
        return mDeviceManager.getUpdateLoop();
    }

    public UpdateLoop getMainUpdateLoop(){
        return mDeviceManager.getMainUpdateLoop();
    }



    public static boolean stringIsEmpty(String str) {
        return str == null || str.length() == 0 || str.equals("")
                || str.equals("null");
    }

    public ArrayList<BTClassicDevice> getList()
    {
        return m_list;
    }



    public boolean has(BTClassicDevice device) {
        for( int i = 0; i < m_list.size(); i++ ) {
            BleDevice device_ith = m_list.get(i);

            if( device_ith == device )  return true;
        }

        return false;
    }

    public BTClassicDevice get(int i)
    {
        return m_list.get(i);
    }



    int getCount()
    {
        return m_list.size();
    }

    public BTClassicDevice getDevice(String uniqueId)
    {
        Log.d(TAG, "map: "+m_map.toString());
        return m_map.get(uniqueId);
    }

    public void add(BTClassicDevice device) {

        if( m_map.containsKey(device.getMacAddress()) ) {
            Log.d(TAG,"Already registered device " + device.getMacAddress());

            return;
        }
        m_list.add(device);
        m_map.put(device.getMacAddress(), device);
    }

    public void remove(BTClassicDevice device) {
        m_list.remove(device);
        m_map.remove(device.getMacAddress());
    }



    void disconnectAll() {
        for( int i = m_list.size()-1; i >= 0; i-- )
        {
            final BleDevice device = get(i);

            device.disconnect();
        }
    }

    /**  处理各种设备的各种错误 */
    public void uhOh(final BTClassicDevice device,final String error){
        Log.e(TAG,error);
        //没啥太好的办法,断开重来吧.
        if( postNeeded() ) {
            post(new Runnable() {
                @Override
                public void run() {
                    device.disconnect();
                }
            });
        } else {
            device.disconnect();
        }
    }


}
