package com.example.imlinkclient;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.imlinkclient.helpr.BluetoothHelper;
import com.example.imlinkclient.helpr.MLinkServiceHelper;
import com.example.imlinkclient.helpr.WifiHelper;
import com.example.imlinkclient.utils.DataConvertUtils;

import java.lang.ref.WeakReference;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;

public class MainClientActivity extends Activity implements View.OnClickListener {
    public final static String TAG = "MainClientActivity";
    private static final int REQUEST_ENABLE_BT = 3;
    private Button mBtnBindAIDL;
    private Button mBtnBindBluetooth;
    private Button mBtnWIFIConnect;
    private Button mBtnTest;
    private ListView mListView;
    private BluetoothHelper mBluetoothHelper;
    private ArrayAdapter<String> mArrayAdapter;
    private boolean isBTConnecting = false;
    private MainHandler mainHandler;
    private ProgressDialog mProgressDialog;
    private TextView mTvStatusAIDL;
    private TextView mTvStatusBT;
    private NetworkConnectChangedReceiver mNetworkConnectChangedReceiver;
    private BlePairBroadcastReceiver mBlePairBroadcastReceiver;
    private static String mSsid;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initHandler();
        initView();
        initReceiver();
        initWifi();
        initBluetooth();
    }

    private void initReceiver() {
        // 蓝牙广播
        mBlePairBroadcastReceiver = new BlePairBroadcastReceiver();
        registerReceiver(mBlePairBroadcastReceiver, new IntentFilter(BluetoothDevice.ACTION_PAIRING_REQUEST));
        // wifi广播
        registerNetworkConnectChangeReceiver();
    }


    private void initBluetooth() {
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (bluetoothAdapter == null) {
            // Device doesn't support Bluetooth
            toast("当前设备不支持蓝牙");
            return;
        }
        if (!bluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        }
    }

    private void initHandler() {
        mainHandler = new MainHandler(MainClientActivity.this);
        mBluetoothHelper = new BluetoothHelper(mainHandler);
        MLinkServiceHelper.getInstance().setHandler(mainHandler);
    }

    private void initWifi() {
        if (!WifiHelper.getInstance().isWifiEnabled()) {
            showAlertDialog("WIFI", "wifi还没打开，要打开吗？", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    WifiHelper.getInstance().openWiFi();
                }
            });
        }
    }


    private void initView() {
        mTvStatusAIDL = (TextView) findViewById(R.id.tv_bind_status_service);
        mTvStatusBT = (TextView) findViewById(R.id.tv_bind_status_bt);
        mBtnBindAIDL = (Button) findViewById(R.id.btn_bind_aidl);
        mBtnBindBluetooth = (Button) findViewById(R.id.btn_bind_bluetooth);
        mBtnWIFIConnect = (Button) findViewById(R.id.btn_wifi_connect);
        mBtnTest = (Button) findViewById(R.id.btn_test);
        mBtnBindBluetooth.setOnClickListener(this);
        mBtnWIFIConnect.setOnClickListener(this);
        mBtnBindAIDL.setOnClickListener(this);
        mBtnTest.setOnClickListener(this);

        mListView = (ListView) findViewById(R.id.lv_bt_data);
        mArrayAdapter = new ArrayAdapter<String>(MainClientActivity.this, R.layout.message);
        mListView.setAdapter(mArrayAdapter);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_bind_aidl:
                // 绑定AIDL服务
                MLinkServiceHelper.getInstance().bindMLinkService();
                showProgress("连接AIDL服务");
                mainHandler.postDelayed(mTimeOutRunnable, 60000);
                break;
            case R.id.btn_bind_bluetooth:
                clickBluetooth();
                break;
            case R.id.btn_wifi_connect:
                // 测试用
                toast("连接wifi");
                WifiHelper.getInstance().connectWifi("MX-vip", "mxcneeds");
                break;
            case R.id.btn_test:
                // 测试用
                String text = (String) mTvStatusAIDL.getText();
                if (text.contains("成功")) {
                    byte[] bytes = new byte[2];
                    bytes[0] = 0;
                    bytes[1] = 1;
                    boolean b = false;
                    try {
                        b = MLinkServiceHelper.getInstance().getmIMlinkService().onWifiConnectionStatus(true, "test");
                        toast("onWifiConnectionStatus : " + b);
                        b = MLinkServiceHelper.getInstance().getmIMlinkService().onBtConnectionStatus(true, "test");
                        toast("onBtConnectionStatus : " + b);
                        b = MLinkServiceHelper.getInstance().getmIMlinkService().onReceivedBtData(bytes);
                        toast("onReceivedBtData : " + b);
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                    toast("status " + b);
                } else {
                    toast("请先连接");
                }

                break;
        }
    }

    private void clickBluetooth() {
        if (!isBTConnecting) {
            showAlertDialog("提示", "请确定车机已经打开Apple CarPlayd 蓝牙连接画面哦！", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    showProgress("请稍等, 如果车机出现配对码界面，请直接在车机点击 确定 ");
                    Log.e(TAG, " start progress");
                    mainHandler.postDelayed(mTimeOutRunnable, 90000);
                    // BMW 45831的蓝牙地址： 28:56:C1:05:2C:B3 ， BMW 36493的蓝牙地址： A0:56:B2:E8:84:85
                    final BluetoothDevice remoteDevice = BluetoothAdapter.getDefaultAdapter().getRemoteDevice("A0:56:B2:E8:84:85");
                    Log.e(TAG, " getRemoteDevice");

                    if (remoteDevice != null) {
                        mBluetoothHelper.startAcceptThread();
                        Log.e(TAG, " startAcceptThread");
                        Log.e("MainClientActivity", " startAcceptThread");

                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                mBluetoothHelper.startConnectThread(remoteDevice);
                            }
                        }, 200);
                    } else {
                        Toast.makeText(MainClientActivity.this, "remoteDevice == null", Toast.LENGTH_SHORT).show();
                    }
                    mBtnBindBluetooth.setText("停止绑定蓝牙");
                }
            });

        } else {
            mBluetoothHelper.unpairDevice();
            mBluetoothHelper.stopAll();
            mArrayAdapter.clear();
            mBtnBindBluetooth.setText("绑定蓝牙");
        }
        isBTConnecting = !isBTConnecting;
    }


    public static class MainHandler extends Handler {
        // 蓝牙状态改变
        public static final int MSG_BT_STATUS = 0x01;
        // 蓝牙数据收receiver
        public static final int MSG_BT_DATA_R = 0x02;
        // 蓝牙数据发transfer
        public static final int MSG_BT_DATA_T = 0x03;
        // WIFI配置信息
        public static final int MSG_WIFI_CONFIG = 0x04;
        // AIDL服务端绑定状态
       public static final int MSG_AIDL_STATUS = 0x06;

        private WeakReference<MainClientActivity> mWeakReference;

        public MainHandler(MainClientActivity activity) {
            mWeakReference = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            MainClientActivity mainActivity = mWeakReference.get();
            Bundle bundle = msg.getData();
            switch (msg.what) {
                case MSG_BT_STATUS:
                    mainActivity.toast("连接状态：" + (msg.arg1 == BluetoothHelper.STATE_CONNECTED));
                    boolean b1 = MLinkServiceHelper
                            .getInstance()
                            .onBtConnectionStatus(msg.arg1 == BluetoothHelper.STATE_CONNECTED,
                                    (String) msg.obj);
                    mainActivity.toast("设置蓝牙状态onBtConnectionStatus ：" + b1);
                    mainActivity.mTvStatusBT.setText(msg.arg1 == BluetoothHelper.STATE_CONNECTED? "连接成功": "未连接");
                    mainActivity.cancelProgress();
                    mainActivity.mainHandler.removeCallbacks(mainActivity.mTimeOutRunnable);

                    if (msg.arg1 ==BluetoothHelper.STATE_NONE &&mainActivity.isBTConnecting == true && mainActivity.mBtnBindBluetooth != null) {
                        // 蓝牙连接断开，把状态改回 蓝牙未连接 状态
                        mainActivity.clickBluetooth();
                    }
                    break;
                case MSG_BT_DATA_R:
                    byte[] readBuf = (byte[]) msg.obj;
                    byte[] buffer = new byte[msg.arg1];
                    System.arraycopy(readBuf, 0, buffer, 0, msg.arg1);
                    boolean b = MLinkServiceHelper.getInstance().onReceivedBtData(buffer);
                    mainActivity.toast("发送数据状态onReceivedBtData ：" + b);
                    mainActivity.mArrayAdapter.add("从车机接收 ： "+Arrays.toString(buffer));
                    Log.d(TAG, "从车机接收 ： " + Arrays.toString(buffer));
//                    mainActivity.mArrayAdapter.add("从车机接收 ： "+ DataConvertUtils.toBinaryString(buffer));
                    break;
                case MSG_BT_DATA_T:
                    byte[] btData = bundle.getByteArray(Constants.KEY_BT_BYTES);
//                    Log.d(TAG, "btData.length : " +btData.length);
//                    byte[] btData = (byte[]) msg.obj;
//                    byte[] realBytes = mainActivity.getRealBytes(btData);

                    Log.d("MLinkServiceHelper", "handler btData.length : " +btData.length);
                    mainActivity.mBluetoothHelper.write(btData);
                    mainActivity.mArrayAdapter.add("写入到车机 ： "+ Arrays.toString(btData));
                    Log.d(TAG, "写入到车机 ： "+ Arrays.toString(btData));

                    break;
                case MSG_WIFI_CONFIG:
                    Bundle data = msg.getData();
                    mSsid = data.getString(Constants.KEY_SSID_STR);
                    String password = data.getString(Constants.KEY_PASS_STR);
                    WifiHelper.getInstance().connectWifi(mSsid, password);
                    break;
                case MSG_AIDL_STATUS:
                    mainActivity.cancelProgress();
                    mainActivity.mainHandler.removeCallbacks(mainActivity.mTimeOutRunnable);
                    int status = msg.arg1;
                    if (status == 1) {
                        mainActivity.toast("AIDL连接成功");
                        mainActivity.mTvStatusAIDL.setText("AIDL连接成功");
                        mainActivity.mBtnBindAIDL.setClickable(false);
                    } else {
                        mainActivity.toast("AIDL连接断开");
                        mainActivity.mTvStatusAIDL.setText("AIDL连接断开");
                        mainActivity.mBtnBindAIDL.setClickable(true);
                    }
                    break;
                default:
                    break;
            }
        }
    }

    public void toast(String msg) {
        Toast.makeText(MainClientActivity.this, msg, Toast.LENGTH_SHORT).show();
    }

    public class BlePairBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction() == BluetoothDevice.ACTION_PAIRING_REQUEST) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                int pin = intent.getIntExtra(BluetoothDevice.EXTRA_PAIRING_KEY, 1234);
                toast("pin : " + pin + " 请在车机点击确定");
                device.setPin(("" + pin).getBytes());
                try {
                    // 这里是系统权限，需要系统签名
                    setPairingConfirmation(BluetoothDevice.class, device, true);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }
    }

    public void setPairingConfirmation(Class<?> btClass, BluetoothDevice device, boolean isConfirm) throws Exception {
        Method setPairingConfirmation = btClass.getDeclaredMethod("setPairingConfirmation", boolean.class);
        setPairingConfirmation.invoke(device, isConfirm);
    }

    private void showAlertDialog(String title, String message, DialogInterface.OnClickListener listener) {
        new AlertDialog.Builder(this).setIcon(R.mipmap.ic_launcher).setTitle(title)
                .setMessage(message).setPositiveButton("确定", listener).create().show();
    }

    private void showProgress(String message) {
        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);//转盘
        mProgressDialog.setCancelable(false);
        mProgressDialog.setCanceledOnTouchOutside(false);
        mProgressDialog.setTitle("提示");
        mProgressDialog.setMessage(message);
        mProgressDialog.show();
    }

    private void cancelProgress() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.cancel();
        }
    }

    Runnable mTimeOutRunnable = new Runnable() {
        @Override
        public void run() {
            cancelProgress();
            toast("连接失败，请稍后重试！");
            if (isBTConnecting == true && mBtnBindBluetooth != null) {
                clickBluetooth();
            }
        }
    };

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_ENABLE_BT:
                if (resultCode == Activity.RESULT_OK) {
                } else {
                    Log.d(TAG, "BT not enabled");
                    Toast.makeText(MainClientActivity.this, "请开启蓝牙",
                            Toast.LENGTH_SHORT).show();
                    MainClientActivity.this.finish();
                }
        }
    }

    private void registerNetworkConnectChangeReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        filter.addAction(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
        filter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
        mNetworkConnectChangedReceiver = new NetworkConnectChangedReceiver();
        registerReceiver(mNetworkConnectChangedReceiver, filter);
    }

    class NetworkConnectChangedReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(action)) {
                Parcelable parcelableExtra = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
                WifiInfo wifiInfo = intent.getParcelableExtra(WifiManager.EXTRA_WIFI_INFO);
                if (wifiInfo != null) {
                    String ssid = wifiInfo.getSSID();
                    if (null != parcelableExtra) {
                        if(("\""+mSsid+"\"").equals(ssid)) {
                            String bssid = intent.getStringExtra(WifiManager.EXTRA_BSSID);
                            NetworkInfo networkInfo = (NetworkInfo) parcelableExtra;
                            NetworkInfo.State state = networkInfo.getState();
                            MLinkServiceHelper.getInstance().onWifiConnectionStatus(state == NetworkInfo.State.CONNECTED, bssid);
                        }
                    }
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unRegisterReceiver();
    }

    private void unRegisterReceiver() {
        if (mNetworkConnectChangedReceiver != null) {
            unregisterReceiver(mNetworkConnectChangedReceiver);
        }
        if (mBlePairBroadcastReceiver != null) {
            unregisterReceiver(mBlePairBroadcastReceiver);
        }
    }


}
