package com.chinapnr.pos.pay.demo.hw;

import android.os.Bundle;
import android.view.View;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.chinapnr.pos.config.PnrResponseKey;
import com.chinapnr.pos.pay.demo.R;
import com.chinapnr.pos.trans.PnrService;
import com.chinapnr.pos.trans.PnrTransListener;
import com.google.gson.Gson;

import java.util.Map;

import timber.log.Timber;

public class ScanActivity extends AppCompatActivity {

    TextView tvRequest, tvResult;
    private View view_line;
    private boolean isFront = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scan);
        view_line = findViewById(R.id.view_line);
        tvRequest = findViewById(R.id.tv_request);
        tvResult = findViewById(R.id.tv_result);

        ((RadioGroup)findViewById(R.id.radio_scan)).setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.radio_front){
                    Timber.d("选中前置摄像头");
                    isFront = true;
                }else {
                    Timber.d("选中后置摄像头");
                    isFront = false;
                }
            }
        });
        findViewById(R.id.btn_confirm).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doScan();
            }
        });
    }

    private void doScan(){
        view_line.setVisibility(View.VISIBLE);
        tvRequest.setText("开始扫码" + "\n" + "是否前置：" + isFront);
        PnrService.getInstance(getApplicationContext()).doScan(isFront, new PnrTransListener(){
            @Override
            public void onResult(String response) {
                Timber.e(response);
                Map resultMap = new Gson().fromJson(response, Map.class);
                String responseCode = resultMap.get(PnrResponseKey.KEY_RESPONSECODE).toString();
                if ("00".equals(responseCode)){
                    tvResult.setText("扫码成功："+response);
                }else {
                    tvResult.setText("扫码失败：" + response);
                }
            }
        });
    }
}