package com.creyond.ecgdemo;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.GridView;
import android.widget.TextView;
import com.creyond.sdk.*;
import com.creyond.support.bluetooth.Bluetooth;
import com.creyond.support.bluetooth.Device;
import com.creyond.support.bluetooth.WatchListener;
import com.creyond.support.display.AnalysisCallback;
import com.creyond.support.ui.gl20.EcgGL20View;
import com.ecg.process.Result;
import com.gengqiquan.adapter.adapter.SBAdapter;
import com.gengqiquan.adapter.interfaces.Holder;
import com.gengqiquan.permission.IResult;
import com.gengqiquan.permission.QQPermission;
import com.gengqiquan.qqresult.Func1;
import com.gengqiquan.qqresult.QQResult;

import java.util.ArrayList;
import java.util.List;


public class MainActivity extends BaseActivity {
    EcgGL20View ecg_view;
    TextView tv_state;
    TextView tv_device;
    TextView tv_record;
    TextView tv_connect;
    EcgDisplayer ecgDisplayer;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setTitle("主页");
        hideBack();

        final String userInfo = SharedUtil.getString(this, LoginActivity.Companion.getUSER_INFO());
        if (userInfo != null) {
            user = (User) JsonUtil.fromJson(userInfo, User.class);
            requestPermission();
        }
        ecg_view = findViewById(R.id.ecg_view);
        tv_state = findViewById(R.id.tv_state);
        tv_device = findViewById(R.id.tv_device);

//        if (BuildConfig.DEBUG)
//            TinyDancer.create()
//                    .show(getApplicationContext());

        tv_record = findViewById(R.id.tv_record);
        tv_record.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ecgDisplayer == null) {
                    error("请先连接设备");
                    return;
                }
                if ("开始记录".equals(tv_record.getText().toString())) {
                    tv_record.setText("停止记录");
                    starTime = System.currentTimeMillis();
                    DemoApplication.recording = true;
                    ecgDisplayer.startRecord(null);
                    return;
                }
                tv_record.setText("开始记录");
                DemoApplication.recording = false;
                starTime = 0;
                ecgDisplayer.stopRecord();
                report(ecgDisplayer.getRecordPath());
            }
        });
        tv_connect = findViewById(R.id.tv_connect);

        tv_connect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if ("连接设备".equals(tv_connect.getText().toString())) {
                    QQResult.startActivityWith(MainActivity.this, DeviceListActivity.class)
                            .result(new Func1() {
                                @Override
                                public void result(Intent intent) {
                                    String json = intent.getStringExtra("device");
                                    device = (Device) JsonUtil.fromJson(json, Device.class);
//                                    SharedUtil.putString(MainActivity.this, "device", json);
                                    watch(device);
                                    tv_connect.setText("断开设备");
                                }
                            });
                    return;
                }

                if ("开始记录".equals(tv_record.getText().toString())) {
                    ecg_view.clear();
                    device.destroy();
                    tv_connect.setText("连接设备");
                    ecgDisplayer = null;
                    init();
                    return;
                }

                tv_record.setText("开始记录");
                ecg_view.clear();
                device.destroy();
                tv_connect.setText("连接设备");
                stop();

                init();

            }
        });
        findViewById(R.id.tv_other).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                QQResult.startActivityWith(MainActivity.this, OtherActivity.class)
                        .result(new com.gengqiquan.qqresult.IResult() {
                            @Override
                            public void result(Intent intent) {
                                user = null;
                                ecg_view.clear();
                                if (device != null) {
                                    device.destroy();
                                }
                                tv_connect.setText("连接设备");
                                init();
                            }

                            @Override
                            public void cancel() {

                            }
                        });

            }
        });
        sbAdapter = new SBAdapter<TagInfo>(this)
                .layout(R.layout.list_item_1)
                .bindViewData(new com.gengqiquan.adapter.interfaces.Converter<TagInfo>() {
                    @Override
                    public void convert(Holder holder, final TagInfo item) {
                        holder.setText(R.id.tv_label, item.label);
                        holder.setText(R.id.tv_value, item.value + "");
                    }
                });
        GridView gv_info = findViewById(R.id.gv_info);
        gv_info.setAdapter(sbAdapter);
        init();
    }

    void stop() {

        DemoApplication.recording = false;
        starTime = 0;
        if (ecgDisplayer.isStart())
            ecgDisplayer.stopRecord();
        report(ecgDisplayer.getRecordPath());
        ecgDisplayer = null;
    }

    private void checkLogin() {
        if (user == null) {
            QQResult.startActivityWith(this, LoginActivity.class)
                    .result(new com.gengqiquan.qqresult.IResult() {
                        @Override
                        public void result(Intent intent) {
                            user = intent.getParcelableExtra(LoginActivity.Companion.getUSER_INFO());
                            requestPermission();
                        }

                        @Override
                        public void cancel() {
                            finish();
                        }
                    });
        }
    }


    void initSDK() {
        Verify.Builder builder = new Verify.Builder("fortest".equals(BuildConfig.FLAVOR) ? "666666" : "92bd3aea95be459dbe1414c9fecc9b2d", user.name)
                .age(user.age)
                .height(user.height)
                .weight(user.weight)
                .phone(user.phone)
                .sex("女".equals(user.sex) ? Verify.Sex.WOMAN : Verify.Sex.MAN);
        if ("fortest".equals(BuildConfig.FLAVOR)) {
            builder.forTest();
        }
        EcgSDK.init(this, builder.build(), new EcgSDK.CallBack() {
            @Override
            public void success() {

            }

            @Override
            public void error(InitResult errorMsg) {
                new AlertDialog.Builder(MainActivity.this)
                        .setMessage(errorMsg.msg)
                        .setNegativeButton("确认", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                finish();
                            }
                        })
                        .show();

            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        getWindow().getDecorView().setKeepScreenOn(SharedUtil.getBoolean(this, "screen_on", true));
        checkLogin();

    }

    User user;
    long starTime = 0;

    private void report(String recordPath) {
        long stopTime = System.currentTimeMillis();
        Report report = new Report(recordPath, ecgDisplayer.getStartTime(), ecgDisplayer.getStopTime(), ecgDisplayer.getHeartRate(), ecgDisplayer.getMinHeartRate(), ecgDisplayer.getMaxHeartRate(), ecgDisplayer.getStep());
        SharedUtil.putString(this, "record", JsonUtil.toJson(report));
        startActivity(new Intent(MainActivity.this, PlaybackActivity.class));
    }

    SBAdapter sbAdapter;
    Device device;

    private void watch(final Device device) {
        this.device = device;
        ecgDisplayer = new EcgDisplayer.Builder(device.getMac(), ecg_view)
                .turnDistance(30)
                .newDisplayer();
        ecgDisplayer.startRecord(null);
        device.watch(new WatchListener() {
            @Override
            public void accept(byte[] src) {
                if (ecgDisplayer == null) {
                    return;
                }
                ecgDisplayer.capture(src, new AnalysisCallback() {
                    @Override
                    public void result(Result result) {
                        updateInfo(result);
                    }
                });
            }

            @Override
            public void disConnected() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tv_state.setText("设备断开");
                        tv_device.setText("--");
                    }
                });
            }


            @Override
            public void connected() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tv_state.setText("连接成功");
                        tv_device.setText(device.getID());
                    }
                });

            }

            @Override
            public void start() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tv_state.setText("正在连接");
                    }
                });
            }

            @Override
            public void fail(final String msg) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tv_state.setText(msg);
                    }
                });
            }


        });
    }


    @SuppressLint("DefaultLocale")
    private void updateInfo(Result result) {
        long stopTime = System.currentTimeMillis();
        String time = "--";
        if (starTime > 0) {
            time = (stopTime - starTime) / 1000 + "";
        }
        List<TagInfo> list = new ArrayList();
        list.add(new TagInfo("当前状态", result.getMotionStateDes()));
        list.add(new TagInfo("记录时间", time));
        list.add(new TagInfo("设备电量", result.getBat() + "%"));
        list.add(new TagInfo("即时心率", result.getHeartRate() > 0 ? result.getHeartRate() : 0));
        list.add(new TagInfo("节律比例", String.format("%.2f", result.getRP()) + "%"));
        list.add(new TagInfo("RR间期", result.getRR()));
        list.add(new TagInfo("步数", result.getStepCount()));
        list.add(new TagInfo("代谢当量值", String.format("%.2f", result.getMetArr())));
        list.add(new TagInfo("步频", (int) (result.getStepRate() * 60) + "步/分"));

//        list.add(new TagInfo("mets", result.getMetArr()));
//        list.add(new TagInfo("转身次数", result.getTurnCount()));
        sbAdapter.appendList(list);
    }

    private void init() {
        List<TagInfo> list = new ArrayList();
        list.add(new TagInfo("当前状态", "--"));
        list.add(new TagInfo("记录时间", "--"));
        list.add(new TagInfo("设备电量", "--"));
        list.add(new TagInfo("即时心率", "--"));
        list.add(new TagInfo("节律比例", "--"));
        list.add(new TagInfo("RR间期", "--"));
        list.add(new TagInfo("步数", "--"));
        list.add(new TagInfo("代谢当量值", "--"));
        list.add(new TagInfo("步频", "--"));
//        list.add(new TagInfo("mets", "--"));
//        list.add(new TagInfo("转身次数", "--"));
        sbAdapter.appendList(list);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (device != null) {
            device.destroy();
        }
        Bluetooth.destroy();
        Log.d(TAG, "onDestroy");
    }


    @Override
    protected void onResume() {
        super.onResume();

        ecg_view.resume();
    }


    @Override
    protected void onPause() {
        super.onPause();
        ecg_view.pause();
    }

    void requestPermission() {
        QQPermission.with(
                this,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION
        ).requestPermissions(new IResult() {
            @Override
            public void permit() {
                initSDK();
            }

            @Override
            public void refuse(List<String> list) {
                finish();
            }
        });

    }

    final static String TAG = "Bluetooth";

    public class TagInfo {
        public String label;
        public Object value;

        public TagInfo(String label, Object value) {
            this.label = label;
            this.value = value;
        }
    }

    @Override
    public void onBackPressed() {
        if (DemoApplication.recording) {
            error("当前正在记录，请稍后退出");
            return;
        }
        super.onBackPressed();
    }
}
