package com.handset.serialportsensor.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.google.common.base.Splitter;
import com.google.gson.Gson;
import com.handset.serialportlib.ByteUtils;
import com.handset.serialportsensor.R;
import com.handset.serialportsensor.bean.RawData;
import com.handset.serialportsensor.bean.MetaData;
import com.handset.serialportsensor.bean.ThresholdBean;
import com.handset.serialportsensor.constant.Constant;
import com.handset.serialportsensor.presenter.SurfaceContract;
import com.handset.serialportsensor.presenter.SurfacePresenter;
import com.handset.serialportsensor.utils.Slog;
import com.handset.serialportsensor.utils.SpUtil;
import com.handset.serialportsensor.utils.ToastHelper;
import com.handset.serialportsensor.utils.PersistHelper;
import com.handset.serialportsensor.utils.StatusBarUtils;
import com.handset.serialportsensor.utils.Utils;
import com.handset.serialportsensor.widget.DashBoard;

import java.text.DecimalFormat;

public class Main2Activity extends BaseActivity implements SurfaceContract.ISerialView {
    private static final String logTag = "HANDSET-JE002-EX";

    private Integer baudRate = 38400;
    private final static String FLOAT_TYPE = "0.00";
    private final static int STARTING_TIMEOUT = 3000;
    private final static int SAVING_TIMEOUT = 7000;
    private final static int WATCHDOG_TIMEOUT = 1000;
    private static boolean readBtnStatusOpen = false;
    private final static String DEFAULT_VALUE = "- - -";

    private static ThresholdBean thresholdBean;
    private SurfacePresenter mPresenter;
    private static MetaData metaData = MetaData.builder().build();
    private DashBoard mDashBoardTemperature;
    private DashBoard mDashBoardHumidity;
    private DashBoard mDashBoardInnerPressure;
    private DashBoard mDashBoardOuterPressure;
    private DashBoard mDashBoardDiffPressure;

    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };

    private Handler mHandlerResetReadBtn = new Handler();
    private Runnable mRunnableResetReadBtn;

    private Handler mHandlerSaveClose = new Handler();
    private Runnable mRunnableSaveClose;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        StatusBarUtils.setTranslucentStatus(this);
        StatusBarUtils.setStatusColor((this), (false), (true), R.color.white);
        setContentView(R.layout.activity_main2);
        initView();
        disableSettingBtn();
        thresholdBean = new Gson().fromJson((String) SpUtil.get((this), Constant.THRESHOLD_KEY, ("")), ThresholdBean.class);
        if (thresholdBean == null) {
            Log.i(logTag, ("onCreate: thresholdBean null"));
            thresholdBean = ThresholdBean.builder()
                    .temperatureFloor("-40").temperatureCeiling("65")
                    .humidityFloor("0").humidityCeiling("100")
                    .innerPressureFloor("80").innerPressureCeiling("150")
                    .outerPressureFloor("80").outerPressureCeiling("150")
                    .diffPressureFloor("-20").diffPressureCeiling("30")
                    .build();
        }
        SpUtil.put((this), Constant.THRESHOLD_KEY, new Gson().toJson(thresholdBean));
        Slog.i(logTag, ("onCreate, thresholdBean value: " + thresholdBean));
        //Slog.save(logTag, ("onCreate, thresholdBean value: " + thresholdBean));

        mPresenter = new SurfacePresenter((this));
        mPresenter.initBLNStatus('0');

        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            if (ActivityCompat.checkSelfPermission((this), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions((this), PERMISSIONS_STORAGE, (1));
            }
        }

        // emulator
        //initEmulator();
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.i(logTag, ("onPause, close bln"));
    }

    @Override
    protected void onResume() {
        super.onResume();
        Slog.i(logTag, ("onResume, open bln"));

        thresholdBean = new Gson().fromJson((String) SpUtil.get((this), Constant.THRESHOLD_KEY, ("")), ThresholdBean.class);
        if (thresholdBean == null) {
            Log.i(logTag, ("onResume: thresholdBean null"));
        }
        if (thresholdBean != null) {
            if (mDashBoardTemperature != null && mDashBoardTemperature.textStart != null) {
                mDashBoardTemperature.textStart = thresholdBean.temperatureFloor;
            }

            if (mDashBoardTemperature != null && mDashBoardTemperature.textEnd != null) {
                mDashBoardTemperature.textEnd = thresholdBean.temperatureCeiling;
            }

            //
            if (mDashBoardHumidity != null && mDashBoardHumidity.textStart != null) {
                mDashBoardHumidity.textStart = thresholdBean.humidityFloor;
            }

            if (mDashBoardHumidity != null && mDashBoardHumidity.textEnd != null) {
                mDashBoardHumidity.textEnd = thresholdBean.humidityCeiling;
            }

            //
            if (mDashBoardInnerPressure != null && mDashBoardInnerPressure.textStart != null) {
                mDashBoardInnerPressure.textStart = thresholdBean.innerPressureFloor;
            }
            if (mDashBoardInnerPressure != null && mDashBoardInnerPressure.textEnd != null) {
                mDashBoardInnerPressure.textEnd = thresholdBean.innerPressureCeiling;
            }

            //
            if (mDashBoardOuterPressure != null && mDashBoardOuterPressure.textStart != null) {
                mDashBoardOuterPressure.textStart = thresholdBean.outerPressureFloor;
            }
            if (mDashBoardOuterPressure != null && mDashBoardOuterPressure.textEnd != null) {
                mDashBoardOuterPressure.textEnd = thresholdBean.outerPressureCeiling;
            }

            //
            if (mDashBoardDiffPressure != null && mDashBoardDiffPressure.textStart != null) {
                mDashBoardDiffPressure.textStart = thresholdBean.diffPressureFloor;
            }
            if (mDashBoardDiffPressure != null && mDashBoardDiffPressure.textEnd != null) {
                mDashBoardDiffPressure.textEnd = thresholdBean.diffPressureCeiling;
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i(logTag, ("main activity destroy"));
        mHandlerResetReadBtn.removeCallbacks(mRunnableResetReadBtn);
        mPresenter.close();
        mPresenter.onDestroy();
    }

    private void initView() {
        mDashBoardTemperature = findViewById(R.id.dashboard_temperature);
        mDashBoardHumidity = findViewById(R.id.dashboard_humidity);
        mDashBoardInnerPressure = findViewById(R.id.dashboard_inner_pressure);
        mDashBoardOuterPressure = findViewById(R.id.dashboard_outer_pressure);
        mDashBoardDiffPressure = findViewById(R.id.dashboard_diff_pressure);
    }

    @SuppressWarnings(value = "unused")
    private void initEmulator() {
        mDashBoardTemperature.setSecondText("26.97");
        mDashBoardHumidity.setSecondText("31.61");
        mDashBoardInnerPressure.setSecondText("102.55");
        mDashBoardDiffPressure.setSecondText("-0.76");
        mDashBoardOuterPressure.setSecondText("103.32");
    }

    private void disableSettingBtn() {
        ImageView ivSettings = findViewById(R.id.title_back);
        ivSettings.setImageResource(R.mipmap.settings_disable);
        ivSettings.setEnabled(false);
    }

    private void enableSettingBtn() {
        ImageView ivSettings = findViewById(R.id.title_back);
        ivSettings.setImageResource(R.mipmap.settings);
        ivSettings.setEnabled(true);
    }

    private void disableHistoryBtn() {
        ImageView ivSettings = findViewById(R.id.iv_start);
        ivSettings.setImageResource(R.mipmap.history_disable);
        ivSettings.setEnabled(false);
    }

    private void enableHistoryBtn() {
        ImageView ivSettings = findViewById(R.id.iv_start);
        ivSettings.setImageResource(R.mipmap.history);
        ivSettings.setEnabled(true);
    }

    public void onClickBtnRead(View view) {
        clearDashBoard();
        if (!readBtnStatusOpen) {
            disableSettingBtn();
            disableHistoryBtn();
            readBtnToStartingState();
            new Thread(
                    () -> {
                        Looper.prepare();
                        new Handler().post(() -> mPresenter.open());
                        Looper.loop();
                    }
            ).start();
        } else {
            mPresenter.close();
            resetStatus();
            showStopTestDialog();
        }
    }

    private void showStopTestDialog() {
        ToastHelper.showSaveSensorDialog((this), new ToastHelper.OnDialogClickListener() {
            @Override
            public void onOKClickListener(View view) {
                PersistHelper.endTest();
                showSavingDataDialog();
            }

            @Override
            public void onCancelClickListener(View view) {
                PersistHelper.endTest((false));
                showCancelingDataDialog();
            }
        });
    }

    private void showSavingDataDialog() {
        runOnUiThread(() -> {
            AlertDialog alertDialog = ToastHelper.showTipDialog((Main2Activity.this), R.mipmap.img_loading, R.string.saving);
            mRunnableSaveClose = alertDialog::dismiss;
            mHandlerSaveClose.postDelayed(mRunnableSaveClose, SAVING_TIMEOUT);
        });
    }

    private void showCancelingDataDialog() {
        runOnUiThread(() -> {
            AlertDialog alertDialog = ToastHelper.showTipDialog((Main2Activity.this), R.mipmap.img_loading, R.string.canceling);
            mRunnableSaveClose = alertDialog::dismiss;
            mHandlerSaveClose.postDelayed(mRunnableSaveClose, SAVING_TIMEOUT);
        });
    }

    public void onClickSettingBtn(View view) {
        startActivity(new Intent((Main2Activity.this), LoginActivity.class));
    }

    public void onClickHistoryBtn(View view) {
        startActivity(new Intent((Main2Activity.this), HistoryActivity.class));
    }

    @Override
    public void onSerialOpen(boolean isOpen) {
        runOnUiThread(() -> {
            readBtnStatusOpen = isOpen;
            if (isOpen) {
                mRunnableResetReadBtn = () -> {
                    mPresenter.write(genCmd(("FFFFFFFF"), Constant.Command.COMMAND_25));
                    new Thread(
                            () -> {
                                Looper.prepare();
                                new Handler().postDelayed(() -> {
                                    Log.i(logTag, ("metaData sensorNo: " + metaData.getSensorNo()));
                                    if (TextUtils.isEmpty(metaData.getSensorNo())) {
                                        Log.e(logTag, ("watch dog check, no data report!"));
                                        runOnUiThread(() -> {
                                            ToastUtils.showShort(R.string.test_id_error);
                                            new Thread(
                                                    () -> {
                                                        Looper.prepare();
                                                        new Handler().post(() -> {
                                                            mPresenter.close();
                                                        });
                                                        Looper.loop();
                                                    }
                                            ).start();
                                        });
                                    } else {
                                        Log.i(logTag, ("watch dog check, data report normally"));
                                        runOnUiThread(this::readBtnToStopState);
                                    }
                                }, WATCHDOG_TIMEOUT);
                                Looper.loop();
                            }
                    ).start();
                };
                mHandlerResetReadBtn.postDelayed(mRunnableResetReadBtn, STARTING_TIMEOUT);
            } else {
                Log.i(logTag, ("Testing closing"));
                metaData.resetData();
                readBtnToState((false));
                //enableSettingBtn();
                enableHistoryBtn();
            }
        });
    }

    @Override
    public void onSerialBaudRate(Integer baudRate) {
        this.baudRate = baudRate;
    }

    @Override
    public void onSerialData(RawData rawData) {
        String message = rawData.getMessage();
        boolean res = rawData.getItemType() == RawData.TYPE_SEND
                ? doSendMessage(message)
                : doReceiveMessage(message);
        Log.v(logTag, ("res: " + res));
    }

    @Override
    public void onSerialError(Integer errorCode) {
        runOnUiThread(() -> {
            ToastUtils.showShort(R.string.test_btl_error);
            readBtnToOriginState();
            //enableSettingBtn();
            enableHistoryBtn();
        });
    }

    private void setMakerNoView(int text) {
        ((TextView) (findViewById(R.id.tv_maker))).setText(String.valueOf(text));
    }

    private void setSensorNoView(String text) {
        //String textCooked = text.substring(0, 4) + text.substring(5);
        ((TextView) (findViewById(R.id.tv_sensor_no))).setText(text);
    }

    private void setEggNoView(String text) {
        ((TextView) (findViewById(R.id.tv_egg_no))).setText(text);
    }

    private void setEggTypeView(String text) {
        ((TextView) (findViewById(R.id.tv_egg_type))).setText(text);
    }

    private void setConeNoView(String text) {
        ((TextView) (findViewById(R.id.tv_cone_no))).setText(text);
    }

    private void setConeUsedTimesView(String text) {
        ((TextView) (findViewById(R.id.tv_cone_used_times))).setText(text);
    }

    private boolean doReceiveMessage(String contain) {
        try {
            Log.i(logTag, ("doReceiveMessage: " + contain));
            if (contain.length() < 100) {
                doCalcBasicData(contain);
            } else {
                metaData.resetData20Degree();
                for (String data : Splitter.fixedLength(30).split(contain)) {
                    metaData.doCalcMeta(data);
                }
                metaData.doCalcMetaEx();

                boolean valid = metaData.isValid();
                Log.i(logTag, "valid: " + valid);
                if (!valid) {
                    //setStatusAbnormal();
                    return false;
                }

                doPersist(metaData);
                setDashBoard(metaData);
                //setStatusNormal();
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    private boolean doSendMessage(String message) {
        Log.v(logTag, ("Activity send message: " + message));
        return true;
    }

    private void doCalcBasicData(String data) {
        byte[] bytes = ByteUtils.hexStrToBytes(data.substring(0, data.length() - 4));
        switch (bytes[7] & 0xff) {
            case Constant.Command.COMMAND_26:
                metaData.setMakerId(getMakerId(bytes));
                metaData.setSensorNo(getSensorNo(bytes));
                metaData.setSensorNoRadix(getSensorNoRadix(bytes));
                setMakerNoView(metaData.getMakerId());
                setSensorNoView(Utils.getSensorNoShow(metaData.getSensorNo()));
                Log.e(logTag, "sensorNo: " + metaData.getSensorNo());
                PersistHelper.genItem(Integer.valueOf(metaData.getSensorNo()), String.valueOf(this.baudRate));
                //mPresenter.write(genCmd(metaData.getSensorNoRadix(), Constant.Command.COMMAND_27));
                break;
            case Constant.Command.COMMAND_28:
                mPresenter.write(genCmd(metaData.getSensorNoRadix(), Constant.Command.COMMAND_30));
                break;
            case Constant.Command.COMMAND_31:
                metaData.setEggNo(getEggNo(bytes));
                setEggNoView(metaData.getEggNo());
                PersistHelper.saveEggID(metaData.getEggNo());
                mPresenter.write(genCmd(metaData.getSensorNoRadix(), Constant.Command.COMMAND_3E));
                break;
            case Constant.Command.COMMAND_3F:
                metaData.setEggType(getEggType(bytes));
                setEggTypeView(metaData.getEggType());
                PersistHelper.saveEggType(metaData.getEggType());
                mPresenter.write(genCmd(metaData.getSensorNoRadix(), Constant.Command.COMMAND_34));
                break;
            case Constant.Command.COMMAND_35:
                metaData.setConeNo(getConeNo(bytes));
                setConeNoView(metaData.getConeNo());
                PersistHelper.saveConeNo(metaData.getConeNo());
                Log.i(logTag, "sensorNoRadix: " + metaData.getSensorNoRadix());
                mPresenter.write(genCmd(metaData.getSensorNoRadix(), Constant.Command.COMMAND_38));
                break;
            case Constant.Command.COMMAND_39:
                metaData.setConeUsedTimes(getConeUsedTimes(bytes));
                setConeUsedTimesView(metaData.getConeUsedTimes());
                PersistHelper.saveConeUsedTimes(metaData.getConeUsedTimes());
                break;
        }
    }

    private int getMakerId(byte[] bytes) {
        int i = ((bytes[4] & 0xff) << 8) | (bytes[5] & 0xff);
        String s = "0000".concat(String.valueOf(i));
        String s2 = s.substring(s.length() - 4);
        return Integer.valueOf(s2.substring(0, 1));
    }

    private String getSensorNo(byte[] bytes) {
        int no = ((bytes[2] & 0xff) * 100 + (bytes[3] & 0xff)) * 10000 + ((bytes[4] & 0xff) << 8) + (bytes[5] & 0xff);
        String s = "00000000".concat(String.valueOf(no));
        return s.substring(s.length() - 8);
    }

    private String getSensorNoRadix(byte[] bytes) {
        int len = 4;
        byte[] dest = new byte[len];
        System.arraycopy(bytes, 2, dest, 0, len);
        return ByteUtils.bytesToHexStr(dest);
    }

    private String getEggNo(byte[] bytes) {
        int len = bytes[8];
        byte[] dest = new byte[len];
        System.arraycopy(bytes, 9, dest, 0, len);
        ByteUtils.bytesToAscii(dest);
        return ByteUtils.bytesToAscii(dest);
    }

    private String getEggType(byte[] bytes) {
        int len = bytes[8];
        byte[] dest = new byte[len];
        System.arraycopy(bytes, 9, dest, 0, len);
        ByteUtils.bytesToAscii(dest);
        return ByteUtils.bytesToAscii(dest);
    }

    private String getConeNo(byte[] bytes) {
        int len = bytes[8];
        byte[] dest = new byte[len];
        System.arraycopy(bytes, 9, dest, 0, len);
        ByteUtils.bytesToAscii(dest);
        return ByteUtils.bytesToAscii(dest);
    }

    private String getConeUsedTimes(byte[] bytes) {
        int len = bytes[8];
        byte[] dest = new byte[len];
        System.arraycopy(bytes, 9, dest, 0, len);
        ByteUtils.bytesToAscii(dest);
        return ByteUtils.bytesToAscii(dest);
    }

    private void clearDashBoard() {
        mDashBoardTemperature.setSecondText(DEFAULT_VALUE);
        mDashBoardHumidity.setSecondText(DEFAULT_VALUE);
        mDashBoardInnerPressure.setSecondText(DEFAULT_VALUE);
        mDashBoardOuterPressure.setSecondText(DEFAULT_VALUE);
        mDashBoardDiffPressure.setSecondText(DEFAULT_VALUE);
        ((TextView) (findViewById(R.id.tv_20degree_humidity))).setText(DEFAULT_VALUE);
        ((TextView) (findViewById(R.id.tv_20degree_inner_press))).setText(DEFAULT_VALUE);
        ((TextView) (findViewById(R.id.tv_maker))).setText(DEFAULT_VALUE);
        ((TextView) (findViewById(R.id.tv_sensor_no))).setText(DEFAULT_VALUE);
        ((TextView) (findViewById(R.id.tv_egg_no))).setText(DEFAULT_VALUE);
        ((TextView) (findViewById(R.id.tv_egg_type))).setText(DEFAULT_VALUE);
        ((TextView) (findViewById(R.id.tv_cone_no))).setText(DEFAULT_VALUE);
        ((TextView) (findViewById(R.id.tv_cone_used_times))).setText(DEFAULT_VALUE);
    }

    private void setDashBoard(MetaData metaData) {
        boolean isNormal = true;
        if (thresholdBean == null) {
            Log.i(logTag, "thresholdBean is null");

        }
        if (metaData.getTemperature() < Float.valueOf(thresholdBean.getTemperatureFloor()) || metaData.getTemperature() > Float.valueOf(thresholdBean.getTemperatureCeiling())) {
            isNormal = false;
            mDashBoardTemperature.setSecondText(metaData.getTemperature(), (false));
        } else {
            mDashBoardTemperature.setSecondText(metaData.getTemperature(), (true));
        }

        if (metaData.getHumidity() < Float.valueOf(thresholdBean.getHumidityFloor()) || metaData.getHumidity() > Float.valueOf(thresholdBean.getHumidityCeiling())) {
            isNormal = false;
            mDashBoardHumidity.setSecondText(metaData.getHumidity(), (false));
        } else {
            mDashBoardHumidity.setSecondText(metaData.getHumidity(), (true));
        }

        if (metaData.getInnerPressure() < Float.valueOf(thresholdBean.getInnerPressureFloor()) || metaData.getInnerPressure() > Float.valueOf(thresholdBean.getInnerPressureCeiling())) {
            isNormal = false;
            mDashBoardInnerPressure.setSecondText(metaData.getInnerPressure(), (false));
        } else {
            mDashBoardInnerPressure.setSecondText(metaData.getInnerPressure(), (true));
        }

        if (metaData.getOuterPressure() < Float.valueOf(thresholdBean.getOuterPressureFloor()) || metaData.getOuterPressure() > Float.valueOf(thresholdBean.getOuterPressureCeiling())) {
            isNormal = false;
            mDashBoardOuterPressure.setSecondText(metaData.getOuterPressure(), (false));
        } else {
            mDashBoardOuterPressure.setSecondText(metaData.getOuterPressure(), (true));
        }

        if (metaData.getDiffPressure() < Float.valueOf(thresholdBean.getDiffPressureFloor()) || metaData.getDiffPressure() > Float.valueOf(thresholdBean.getDiffPressureCeiling())) {
            isNormal = false;
            mDashBoardDiffPressure.setSecondText(metaData.getDiffPressure(), (false));
        } else {
            mDashBoardDiffPressure.setSecondText(metaData.getDiffPressure(), (true));
        }

        ((TextView) (findViewById(R.id.tv_20degree_humidity))).setText(new DecimalFormat(FLOAT_TYPE).format(metaData.getDegree20Humidity()));
        ((TextView) (findViewById(R.id.tv_20degree_inner_press))).setText(new DecimalFormat(FLOAT_TYPE).format(metaData.getDegree20Pressure()));

        if (isNormal) {
            setStatusNormal();
        } else {
            setStatusAbnormal();
        }
    }

    private void setStatusNormal() {
        ((TextView) (findViewById(R.id.tv_main_status_normal))).setTextColor(getResources().getColor(R.color.param_black_color));
        findViewById(R.id.tv_main_status_normal_round).setBackgroundResource(R.drawable.shape_status_green_round);
        ((TextView) (findViewById(R.id.tv_main_status_err))).setTextColor(getResources().getColor(R.color.status_grey));
        findViewById(R.id.tv_main_status_err_round).setBackgroundResource(R.drawable.shape_status_grey_round);
    }

    private void setStatusAbnormal() {
        ((TextView) (findViewById(R.id.tv_main_status_normal))).setTextColor(getResources().getColor(R.color.status_grey));
        findViewById(R.id.tv_main_status_normal_round).setBackgroundResource(R.drawable.shape_status_grey_round);
        ((TextView) (findViewById(R.id.tv_main_status_err))).setTextColor(getResources().getColor(R.color.param_black_color));
        findViewById(R.id.tv_main_status_err_round).setBackgroundResource(R.drawable.shape_status_red_round);
    }

    private void resetStatus() {
        ((TextView) (findViewById(R.id.tv_main_status_normal))).setTextColor(getResources().getColor(R.color.param_grey_color));
        findViewById(R.id.tv_main_status_normal_round).setBackgroundResource(R.drawable.shape_status_grey_round);
        ((TextView) (findViewById(R.id.tv_main_status_err))).setTextColor(getResources().getColor(R.color.status_grey));
        findViewById(R.id.tv_main_status_err_round).setBackgroundResource(R.drawable.shape_status_grey_round);
    }

    private void readBtnToOriginState() {
        findViewById(R.id.btn_read).setEnabled(true);
        findViewById(R.id.btn_read).setBackgroundResource(R.drawable.bg_start_btn_new);
        ((Button) findViewById(R.id.btn_read)).setText(R.string.start_test);
    }

    private void readBtnToStopState() {
        findViewById(R.id.btn_read).setEnabled(true);
        findViewById(R.id.btn_read).setBackgroundResource(R.drawable.bg_stop_btn_new);
        ((Button) findViewById(R.id.btn_read)).setText(R.string.stop_test);
    }

    private void readBtnToStartingState() {
        findViewById(R.id.btn_read).setBackgroundResource(R.drawable.bg_read_btn_starting);
        ((Button) findViewById(R.id.btn_read)).setText(R.string.read_btn_starting);
        findViewById(R.id.btn_read).setEnabled(false);
    }

    private void readBtnToState(boolean isOpen) {
        findViewById(R.id.btn_read).setEnabled(true);
        findViewById(R.id.btn_read).setBackgroundResource(isOpen ? R.drawable.bg_stop_btn_new : R.drawable.bg_start_btn_new);
        ((Button) findViewById(R.id.btn_read)).setText(isOpen ? R.string.stop_test : R.string.start_test);
    }

    private void doPersist(MetaData metaData) {
        PersistHelper.save(metaData.getTemperature(), Constant.Command.COMMAND_29);
        PersistHelper.save(metaData.getInnerPressure(), Constant.Command.COMMAND_2A);
        PersistHelper.save(metaData.getHumidity(), Constant.Command.COMMAND_2B);
        PersistHelper.save(metaData.getOuterPressure(), Constant.Command.COMMAND_2C);
        PersistHelper.save(metaData.getDiffPressure(), Constant.Command.COMMAND_2D);
        PersistHelper.save(metaData.getDegree20Humidity(), Constant.Command.COMMAND_2E);
        PersistHelper.save(metaData.getDegree20Pressure(), Constant.Command.COMMAND_2F);
    }
}

