package com.stm.asset.page;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.fn.useries.utils.MusicPlayer;
import com.seuic.uhf.UHFService;
import com.stm.asset.R;
import com.stm.asset.base.BaseActivity;
import com.stm.asset.base.StmApplication;
import com.stm.asset.utils.StringUtils;
import com.stm.asset.utils.ViewUtil;
import com.stm.asset.view.LoadingDialog;
import com.stm.asset.view.TextMoveLayout;

/**
 * 类名称：DeviceSetActivity
 * 类描述：设备参数设置
 * 创建人：story
 * 创建时间：2021-12-15 11:10
 */
public class DeviceSetActivity extends BaseActivity implements View.OnClickListener {

    private TextMoveLayout powerLayout;
    private SeekBar powerSb;
    private TextView moveTextDBM;
    private ViewGroup.LayoutParams layoutParams;
    private EditText temperatureEt;
    private Spinner sessionSpinner;
    private Spinner flagSpinner;

    private UHFService uhfService;
    private int screenWidth;
    private boolean firstIn = true;
    private LoadingDialog loadingDialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_device_set);
        initView();
        loadingDialog = new LoadingDialog(this);
    }

    private void initView() {
        initTitle();
        screenWidth = ViewUtil.getScreenWidth(this);
        moveTextDBM = new TextView(this);
        moveTextDBM.setBackgroundColor(Color.rgb(245, 245, 245));
        moveTextDBM.setTextColor(Color.rgb(0, 161, 229));
        moveTextDBM.setTextSize(26);
        moveTextDBM.layout(0, 5, screenWidth, 80);
        titleTxt.setText("设备参数");
        findViewById(R.id.common_title_back_layout).setOnClickListener(this);
        powerLayout = findViewById(R.id.set_power_layout);
        powerSb = findViewById(R.id.set_power_sb);
        powerSb.setOnSeekBarChangeListener(new OnSeekBarChangeListenerImp());
        powerSb.setMax(33);
        layoutParams = new ViewGroup.LayoutParams(screenWidth, 40);

        temperatureEt = findViewById(R.id.set_temperature_et);
        findViewById(R.id.set_temperature_read_btn).setOnClickListener(this);

        sessionSpinner = findViewById(R.id.set_inventory_session_spinner);
        flagSpinner = findViewById(R.id.set_inventory_flag_spinner);

        findViewById(R.id.inventory_save_btn).setOnClickListener(this);

        uhfService = UHFService.getInstance();
    }

    @Override
    protected void onResume() {
        super.onResume();
        uhfService.open();
        powerLayout.removeAllViews();
        powerLayout.addView(moveTextDBM, layoutParams);
        loadingDialog.show();
        if (uhfService != null && firstIn) {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    loadingDialog.dismiss();
                    firstIn = false;
                    getPower();
                    getInventoryParams();
                }
            }, 1500);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        uhfService.close();
    }

    private void getPower() {
        try {
            String outPowerSetParams = String.valueOf(uhfService.getPower());
            Log.i("DeviceSetActivity", "M10_U8：getPower " + outPowerSetParams);
            StmApplication.getInstance().getAppExecutors().mainThread().execute(new Runnable() {
                @Override
                public void run() {
                    refreshPowerView(outPowerSetParams);
                }
            });
        } catch (Exception e) {
            Log.i("DeviceSetActivity", "M10_U8：getPowerParamsException " + e.toString());
        }
    }

    private void getInventoryParams() {
//        String[] mItems = { "s0", "s1", "s2", "s3" };
//        String[] mItemsFlag = { "A", "B" };
//        ArrayAdapter<String> simpleAdapter = new ArrayAdapter<>(this, R.layout.view_simple_spinner_item, mItems);
//        sessionSpinner.setAdapter(simpleAdapter);
//        String sessionParams =  mUSeries.getParams(M11U8Service.SESSIONSTATE);
//        if (sessionParams != null && !"".equals(sessionParams)) {
//            sessionSpinner.setSelection(Integer.parseInt(sessionParams));
//        }
//        simpleAdapter = new ArrayAdapter<>(this, R.layout.view_simple_spinner_item, mItemsFlag);
//        flagSpinner.setAdapter(simpleAdapter);
//        String flagParams =  mUSeries.getParams(M11U8Service.FLAGSTATE);
//        if (flagParams != null && !"".equals(flagParams)) {
//            flagSpinner.setSelection(Integer.parseInt(flagParams));
//        }
    }

    private void refreshPowerView(String powerValue) {
        String str = powerValue + "dBm";
        moveTextDBM.setText(str);
        powerSb.setProgress(Integer.parseInt(powerValue));
    }

    private void getTemperature() {
        temperatureEt.setText("");
        try {
            String strTemperature = uhfService.getTemperature();
            Log.i("DeviceSetActivity", "M10_U8：getTemperature " + strTemperature);
            if (!StringUtils.isEmptyOrNull(strTemperature)) {
                StmApplication.getInstance().getAppExecutors().mainThread().execute(new Runnable() {
                    @Override
                    public void run() {
                        MusicPlayer.getInstance().play(MusicPlayer.Type.OK);
                        temperatureEt.setText(strTemperature);
                    }
                });
            } else {
                MusicPlayer.getInstance().play(MusicPlayer.Type.MUSIC_ERROR);
            }
        } catch (Exception e) {
            Log.i("DeviceSetActivity", "M10_U8：getTemperatureParamsException" + e.toString());
            e.printStackTrace();
        }
    }

    private boolean setSessionAndFlag() {
//        int sessionIndex = sessionSpinner.getSelectedItemPosition();
//        int flagIndex = flagSpinner.getSelectedItemPosition();
//        boolean setSessionStateResult = mUSeries.setParams(M11U8Service.SESSIONSTATE, Byte.toString((byte) sessionIndex));
//        boolean setFlagStateResult = mUSeries.setParams(M11U8Service.FLAGSTATE, Byte.toString((byte) flagIndex));
//        return (setSessionStateResult && setFlagStateResult);
        return true;
    }

    private boolean setPower() {
        String outputPower;
        try {
            String powerStr = moveTextDBM.getText().toString();
            outputPower = powerStr.subSequence(0, powerStr.indexOf("dBm")).toString();
        } catch (Exception e) {
            return false;
        }
        try {
            return uhfService.setPower(Integer.parseInt(outputPower));
        } catch (Exception e) {
            Log.i("DeviceSetActivity", "M10_U8：setPowerParamsException" + e.toString());
            return false;
        }

    }

    private void saveSet() {
        if (setSessionAndFlag() && setPower()) {
            MusicPlayer.getInstance().play(MusicPlayer.Type.OK);
            StmApplication.getInstance().showToastShort("设置成功");
            return;
        }
        StmApplication.getInstance().showToastShort("设置失败");
        MusicPlayer.getInstance().play(MusicPlayer.Type.MUSIC_ERROR);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.common_title_back_layout:
                finish();
                break;
            case R.id.set_temperature_read_btn:
                getTemperature();
                break;
            case R.id.inventory_save_btn:
                saveSet();
                break;
        }
    }

    private class OnSeekBarChangeListenerImp implements SeekBar.OnSeekBarChangeListener {

        // 触发操作，拖动
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            float value = ((float) screenWidth / (float) 35) * (float) 0.8;
            int moveStep = Math.round(value);
            moveTextDBM.setWidth(80);
            moveTextDBM.layout((progress * moveStep), 5, screenWidth, 80);
            String str = progress + "dBm";
            moveTextDBM.setText(str);
        }

        // 表示进度条刚开始拖动，开始拖动时候触发的操作
        public void onStartTrackingTouch(SeekBar seekBar) {
        }

        // 停止拖动时候
        public void onStopTrackingTouch(SeekBar seekBar) {
        }
    }
}
