package com.ycgis.macall.personalcenter.v.activity;

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.os.Bundle;
import android.util.Log;
import android.view.View;

import androidx.recyclerview.widget.LinearLayoutManager;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.rs.macall.androidx.basemodel.base.BaseViewBindActivity;
import com.rs.macall.androidx.basemodel.callback.SimpleListClickListener;
import com.rs.macall.androidx.basemodel.decoration.MyDividerItemDecoration;
import com.rs.macall.androidx.basemodel.utils.ToastUtil;
import com.ycgis.macall.personalcenter.R;
import com.ycgis.macall.personalcenter.databinding.ActivityBluetoothBinding;
import com.ycgis.macall.personalcenter.m.datamodel.PrintModel;
import com.ycgis.macall.personalcenter.util.BluetoothManage;
import com.ycgis.macall.personalcenter.v.adapter.BluetoothListAdapter;
import com.ycgis.zpSDK.BluetoothSocket;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

public class BluetoothActivity extends BaseViewBindActivity<ActivityBluetoothBinding> {
    public static final String EXTRA_BLUETOOTH_DEVICE_ADDRESS = "Bluetooth Device Adrress";
    public static final String EXTRA_BLUETOOTH_DEVICE_NAME = "Bluetooth Device Name";

    public String TAG = "zpSDK";
    public BluetoothAdapter btAdapter = null;
    private BluetoothListAdapter listAdapter1, listAdapter2;
    private List<BluetoothDevice> pdDataList = new ArrayList<>(), searchDataList = new ArrayList<>();

    private boolean isLinkPrinter = false;

    @Override
    protected ActivityBluetoothBinding getViewBinding() {
        return ActivityBluetoothBinding.inflate(getLayoutInflater());
    }

    @Override
    protected void init() {
        viewBinding.rvSearchList.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
        viewBinding.rvSearchList.addItemDecoration(new MyDividerItemDecoration(getContext(), LinearLayoutManager.VERTICAL));
        viewBinding.rvYpd.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
        viewBinding.rvYpd.addItemDecoration(new MyDividerItemDecoration(getContext(), LinearLayoutManager.VERTICAL));
        viewBinding.btnSearch.setVisibility(View.VISIBLE);
        viewBinding.searchProgress.setVisibility(View.GONE);
        viewBinding.btnSearch.setOnClickListener(customClickListener);
    }

    @Override
    protected void readInstanceState(Bundle savedInstanceState) {

    }

    @Override
    protected void start() {
        viewBinding.baseTitle.contentTitle.setText("蓝牙测试");
        viewBinding.baseTitle.leftImage.setImageDrawable(getDrawables(R.drawable.back_cliener));
        boolean init = BluetoothManage.getInstance().init();
        if (!init) {
            ToastUtil.centered(getContext(), "当前设备不支持蓝牙！");
            return;
        }
        if (!BluetoothManage.getInstance().isBluetoothOpen(getActivity(), true)) {
            ToastUtil.centered(getContext(), "请先打开蓝牙！");
            return;
        }
        btAdapter = BluetoothAdapter.getDefaultAdapter();

        bonded_devices_get();

        //register broadcast receiver
        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothDevice.ACTION_FOUND);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        registerReceiver(mBroadcastReceiver, filter);
    }

    @Override
    protected void bindViewClick(View v) {
        if (v.getId() == R.id.titleleft) {
            finish();
            return;
        }

        if (v.getId() == R.id.btn_search) {
            discovry_do();
            return;
        }

        if (v.getId() == R.id.btn_printer) {
            //{"content":"二维码内容","printType":2},{"content":"base64","printType":3}
            String prContent = "[{\"content\":\"皖A97B21\n\",\"printType\":1},{\"content\":\"测试全部中文\",\"printType\":2}]";
            Type type = new TypeToken<List<PrintModel>>() {
            }.getType();
            List<PrintModel> data = new Gson().fromJson(prContent, type);
            boolean b = BluetoothSocket.getInstance().sendData(data);
            if (b) {
                ToastUtil.centered(getContext(),"打印完成");
            } else {
                ToastUtil.centered(getContext(),"打印失败");
//                mAgentWeb.getJsAccessEntrace().quickCallJs("callBluetoothError", "-4", "打印失败！");
            }
        }

    }

    //get the Bonded devices
    //获取配对列表
    private void bonded_devices_get() {
        pdDataList.clear();
        Set<BluetoothDevice> PairedDevices = btAdapter.getBondedDevices();
        if (PairedDevices.size() > 0) {
            for (BluetoothDevice device : PairedDevices) {
//                String device_info = device.getName()+"\n"+device.getAddress();
                pdDataList.add(device);
            }
        }
        initDataPd();
    }

    private void lk(BluetoothDevice device) {
        baseShowDialog("正在链接");
        if (!BluetoothSocket.getInstance().ConnectPrinter(device.getAddress())) {
            //Toast.makeText(this, "Connect Fail", Toast.LENGTH_SHORT).show();
            baseDismissDialog();
            viewBinding.tvPrinter.setText("链接失败");
            viewBinding.btnPrinter.setVisibility(View.GONE);
            isLinkPrinter = false;
        } else {
            baseDismissDialog();
            viewBinding.tvPrinter.setText("已连接:" + device.getName());
            viewBinding.btnPrinter.setVisibility(View.VISIBLE);
            viewBinding.btnPrinter.setOnClickListener(customClickListener);
            isLinkPrinter = true;
        }
    }

    private void initDataPd() {
        if (listAdapter1 == null) {
            listAdapter1 = new BluetoothListAdapter(getContext(), pdDataList);
            viewBinding.rvYpd.setAdapter(listAdapter1);
            listAdapter1.setListClickListener(new SimpleListClickListener() {
                @Override
                public void onSingleClick(View v, int pointer) {
                    lk(listAdapter1.getDataItem(pointer));
                }
            });
        } else {
            listAdapter1.upData(pdDataList);
        }
    }

    /*
     * 获取蓝牙设备，并开始搜索设备
     */
    //search BlueTooth devices
    private void discovry_do() {
        Log.d("BT", "-----------discovry_do---------");
        if (!btAdapter.isEnabled()) {
            btAdapter.enable();
            while (btAdapter.getState() != BluetoothAdapter.STATE_ON) ;
        }
//        setProgressBarIndeterminateVisibility(true);
//        setTitle("Search devices...");
        //获取蓝牙设备，并开始搜索设备
        if (btAdapter.isDiscovering()) {
            Log.d("BT", "-----------btAdapter.cancelDiscovery()---------");
            btAdapter.cancelDiscovery();
        }
        Log.d("BT", "-----------btAdapter.startDiscovery()---------");
        btAdapter.startDiscovery();
        Log.d("BT", "-----------btAdapter.startDiscovery()+END---------");

        viewBinding.btnSearch.setVisibility(View.GONE);
        viewBinding.searchProgress.setVisibility(View.VISIBLE);
    }

    BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            String action = intent.getAction();
            Log.d("BT", "----------onReceive----------" + action);
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                    initSearch(device);
                }
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                setProgressBarIndeterminateVisibility(false);
                setTitle("Choose Device");
                viewBinding.btnSearch.setVisibility(View.VISIBLE);
                viewBinding.searchProgress.setVisibility(View.GONE);
            }
        }
    };

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

    private void initSearch(BluetoothDevice device) {
        if (listAdapter2 == null) {
            searchDataList.add(device);
            listAdapter2 = new BluetoothListAdapter(getContext(), searchDataList);
            viewBinding.rvSearchList.setAdapter(listAdapter2);

            listAdapter2.setListClickListener(new SimpleListClickListener() {
                @Override
                public void onSingleClick(View v, int pointer) {
                    lk(listAdapter2.getDataItem(pointer));
                }
            });
        } else {
            listAdapter2.addItem(device);
        }
    }

}