package aicare.net.cn.sdk.ailinksdkdemoandroid.modules.broadcast_nutrition;

import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

import androidx.annotation.Nullable;

import com.pingwang.bluetoothlib.bean.BleValueBean;
import com.pingwang.bluetoothlib.config.BleConfig;
import com.pingwang.bluetoothlib.listener.OnBleBroadcastDataListener;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import aicare.net.cn.sdk.ailinksdkdemoandroid.R;
import aicare.net.cn.sdk.ailinksdkdemoandroid.base.BleBaseActivity;
import aicare.net.cn.sdk.ailinksdkdemoandroid.utils.L;

public class BroadNutritionActivity extends BleBaseActivity implements View.OnClickListener, OnBleBroadcastDataListener {

    private ListView list_view;
    private Button btn_start;
    private Button btn_stop;
    private Button btn_clear;

    private List<String> mList;
    private ArrayAdapter mListAdapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_broadcast_nutrition);

        list_view = findViewById(R.id.list_view);
        btn_start = findViewById(R.id.btn_start);
        btn_stop = findViewById(R.id.btn_stop);
        btn_clear = findViewById(R.id.btn_clear);

        btn_start.setOnClickListener(this);
        btn_stop.setOnClickListener(this);
        btn_clear.setOnClickListener(this);

        mList = new ArrayList<>();
        mListAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, mList);
        list_view.setAdapter(mListAdapter);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.btn_start) {
            mAILinkBleManager.startScan(0, BleConfig.UUID_SERVER_BROADCAST_AILINK);
        } else if (id == R.id.btn_stop) {
            mAILinkBleManager.stopScan();
        } else if (id == R.id.btn_clear) {
            clearText();
        }
    }

    @Override
    protected void onDestroy() {
        if (mAILinkBleManager != null) {
            mAILinkBleManager.stopScan();
            mAILinkBleManager.removeOnBleBroadcastDataListener(this);
        }
        super.onDestroy();
    }

    @Override
    public void onServiceSuccess() {
        L.i("绑定服务成功");
        mAILinkBleManager.addOnBleBroadcastDataListener(this);
    }

    @Override
    public void onServiceErr() {

    }

    @Override
    public void unbindServices() {

    }

    private String mMac;

    @Override
    public void onBleBroadcastData(BleValueBean bleValueBean, byte[] payload) {
        if (bleValueBean.getCid() == 0x04 && bleValueBean.isBroadcastModule()) {
            mMac = bleValueBean.getMac();
            notifyData(payload);
        }
    }

    private String mOldText = "";
    private SimpleDateFormat mSdf;

    // 添加一条文本
    private void addText(String text) {
        if (mSdf == null) {
            mSdf = new SimpleDateFormat("HH:mm:ss", Locale.US);
        }
        if (mOldText.equals(text)) {
            return;
        }
        mOldText = text;
        String log = mSdf.format(System.currentTimeMillis()) + "：\n" + text;
        mList.add(log);
        mListAdapter.notifyDataSetChanged();
        list_view.smoothScrollToPosition(mList.size() - 1);
    }

    // 清空文本
    private void clearText() {
        mList.clear();
        mListAdapter.notifyDataSetChanged();
    }


    /**
     * 解析数据
     *
     * @param hex payloads
     */
    public void notifyData(byte[] hex) {
        if (hex.length >= 10) {
            int no = hex[0] & 0xff;
            int type = hex[1] & 0xff;
            int weight = ((hex[2] & 0xff) << 16) + ((hex[3] & 0xff) << 8) + (hex[4] & 0xff);
            int unit = (hex[5] & 0xff) & 0x0f;
            int decimal = ((hex[5] & 0xff) & 0x70) >> 4;
            int symbol = (hex[5] & 0xff) >> 7;
            int battery = hex[6] & 0xff;
            int err = hex[7] & 0xff;
            float weightValue = weight;
            if (symbol == 1) {
                weightValue *= -1;
            }
            weightValue /= Math.pow(10, decimal);
            String weightStr = getPreFloatStr(weightValue, decimal);
            addText("Mac：" + mMac + "\n流水号：" + no + "\n测量标识符：" + type + "\n原始重量：" + weight + "，单位：" + unit + "，小数点：" + decimal + "，正负：" + symbol + "\n重量：" + weightStr + "\n电量：" + battery + "\n异常标志位：" + err);
        }
    }

    /**
     * 四舍五入
     *
     * @param f 小数
     * @return float
     */
    protected String getPreFloatStr(float f, int decimal) {
        BigDecimal dc = new BigDecimal(f);
        return dc.setScale(decimal, BigDecimal.ROUND_HALF_UP).toString();
    }


}
