package com.tomastc.anickd;

import static android.view.View.GONE;
import static android.view.View.INVISIBLE;
import static android.view.View.VISIBLE;
import static com.tomastc.anickd.lib.ErrorCode.E103;
import static com.tomastc.anickd.lib.ErrorCode.E108;
import static com.tomastc.anickd.lib.ErrorCode.E111;
import static com.tomastc.anickd.lib.ErrorCode.E112;
import static com.tomastc.anickd.lib.ErrorCode.E114;
import static com.tomastc.anickd.lib.ErrorCode.E122;
import static com.tomastc.anickd.lib.ErrorCode.E124;
import static com.tomastc.anickd.lib.ErrorCode.E203;

import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;

import android.media.RingtoneManager;
import android.media.ToneGenerator;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.keyence.autoid.sdk.scan.DecodeResult;
import com.tomastc.anickd.lib.ActionListenerCallback;
import com.tomastc.anickd.lib.CkdInterface;
import com.tomastc.anickd.lib.ErrorCode;
import com.tomastc.anickd.lib.KeyMapping;
import com.tomastc.anickd.lib.PendingMaster;
import com.tomastc.anickd.lib.ProductionSchedule;
import com.tomastc.anickd.lib.Scanner;
import com.tomastc.anickd.lib.Settings;
import com.tomastc.anickd.lib.SpinAdapter;
import com.tomastc.anickd.lib.User;
import com.tomastc.anickd.lib.common.CallbackListener;
import com.tomastc.anickd.lib.common.MessageListener;
import com.tomastc.anickd.lib.common.StringConvert;
import com.tomastc.anickd.lib.common.StringUtil;
import com.tomastc.anickd.lib.common.Utils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

import okhttp3.WebSocket;

public class StagingActivity_Phase3 extends Scanner implements
        CallbackListener, MessageListener, CkdInterface {

    TextView txt_pc_no, txt_part_no, txt_color, txt_maker, txt_control,txt_chk_point1, txt_chk_point2, txt_chk_point3, txt_chk_point4, lbl_tablet_no, txt_ttl_qty;
    private RelativeLayout  popupLayout1, popupLayout2;
    private SpinAdapter pendingSpinAdapter = null, ngSpinAdapter=null;
    ConstraintLayout content_page2;
    Button btn_main_menu, btn_clear, btn_pending, btn_ng, btn_answer1, btn_answer2, btn_answer3, btn_answer4;
    private JSONArray j_schedules, matched_schedules;
    private int total_remaining = 0;
    private ProductionSchedule.STAGE stage = ProductionSchedule.STAGE.STAGING;
    private JSONObject checkpoint;
    private boolean waiting_ws_response = false;
    private boolean screen_locked = false;
    private String s_qty, part_no, part_color, pc_no, control_no, model_no,  pc_no_scan1, control_no_scan1
            // v1.4.7
            , str_packing_no, case_no;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_staging_phase3);
        default_view = (EditText) findViewById(R.id.txt_tmp);

        WsClient.getInstance().setOnMessageListener(this);

        pc_no_scan1 = "";
        control_no_scan1  = "";

        btn_answer1 = (Button) findViewById(R.id.btn_answer1);
        btn_answer2 = (Button) findViewById(R.id.btn_answer2);
        btn_answer3 = (Button) findViewById(R.id.btn_answer3);
        btn_answer4 = (Button) findViewById(R.id.btn_answer4);
        btn_main_menu = (Button) findViewById(R.id.btn_main_menu);
        btn_clear = (Button) findViewById(R.id.btn_clear);
        btn_pending = (Button) findViewById(R.id.btn_pending);
        btn_ng = (Button) findViewById(R.id.btn_ng);

        txt_pc_no = (TextView) findViewById(R.id.txt_pc_no);
        txt_part_no = (TextView) findViewById(R.id.txt_part_no);
        txt_color = (TextView) findViewById(R.id.txt_color);
        txt_maker = (TextView) findViewById(R.id.txt_maker);
        txt_control = (TextView) findViewById(R.id.txt_control);
        txt_ttl_qty = (TextView) findViewById(R.id.txt_ttl_qty);

        txt_chk_point1 = (TextView) findViewById(R.id.txt_chk_point1);
        txt_chk_point2 = (TextView) findViewById(R.id.txt_chk_point2);
        txt_chk_point3 = (TextView) findViewById(R.id.txt_chk_point3);
        txt_chk_point4 = (TextView) findViewById(R.id.txt_chk_point4);
        lbl_tablet_no = (TextView) findViewById(R.id.lbl_tablet_no);

        content_page2 = (ConstraintLayout) findViewById(R.id.content_page2);
        popupLayout1 = (RelativeLayout) findViewById(R.id.popupLayout1);
        popupLayout2 = (RelativeLayout) findViewById(R.id.popupLayout2);

        try {
            // Set AREA
            WsClient.sendWs(StagingActivity_Phase3.this, new HashMap<String, Object>() {{
                put("area", ProductionSchedule.AREA.STAGING);
            }}, WsProtocol.COMMAND.SET_AREA_REQUEST);
            //staging open
            WsClient.sendWsEventLog(StagingActivity_Phase3.this,
                    null
                    , WsProtocol.EVENT.HT_STAGING_OPEN
                    , ProductionSchedule.STATUS.WORKING
            );
            // Get paired tablet device id
            WsClient.sendWs(StagingActivity_Phase3.this, null, WsProtocol.COMMAND.GET_PAIRED_DEVICE_REQUEST);
        } catch (Exception e) {
            Log.e(getString(R.string.tag), "ERROR: " + e.getMessage());
        }

        btn_main_menu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // stop activity
                finish();
            }
        });
        btn_clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                reset();
            }
        });

        btn_pending.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Check if no schedule load
                if (j_schedules == null) {
                    return;
                }
                // Open pending dialog
                if (pendingSpinAdapter == null) {
                    JSONArray jArray = MainActivity.pendingMasterJsonArray;
                    if (jArray!=null) {

                        try {
                            if (jArray.length() == 0)
                                return;

                            List<PendingMaster> list = new ArrayList<>();
                            for (int i=0;i<jArray.length();i++) {
                                if (jArray.getJSONObject(i).getString("sec").equalsIgnoreCase("pending")) {
                                    String id = jArray.getJSONObject(i).getString("id");
                                    String name = jArray.getJSONObject(i).getString("mesg");

                                    list.add(new PendingMaster(id, name));
                                }
                            }
                            PendingMaster[] pendingMasters = list.toArray(new PendingMaster[0]);

                            Log.d(getString(R.string.tag), Arrays.deepToString(pendingMasters));

                            pendingSpinAdapter = new SpinAdapter(
                                    getApplicationContext(), R.layout.spinner_usr_list, pendingMasters);

                        } catch (Exception e) {
                            Log.e(getString(R.string.tag), "ERROR: " + e.getMessage());
                            alertError(e.getMessage(), new ActionListenerCallback() {
                                @Override
                                public void onActionSuccess(String successMessage) throws Exception {

                                }

                                @Override
                                public void onActionFailure(Throwable throwableError) {

                                }
                            }, screen_locked=false);
                        }
                    }
                }

                if (pendingSpinAdapter.getCount() == 0) {
                    alertError(ErrorCode.E115.toString(), new ActionListenerCallback() {
                        @Override
                        public void onActionSuccess(String successMessage) throws Exception {

                        }

                        @Override
                        public void onActionFailure(Throwable throwableError) {
                            ErrorCode errorCode = ErrorCode.fromId(Integer.parseInt(throwableError.getMessage()));
                            Toast.makeText(StagingActivity_Phase3.this, errorCode.toString(), Toast.LENGTH_LONG)
                                    .show();
                            try {
                                WsClient.sendWsEventLog(StagingActivity_Phase3.this,
                                        new HashMap<String, Object>() {{
                                            put("event_det", WsProtocol.EVENT.HT_STAGING_PENDING);
                                            put("error_code", errorCode.getId());
                                            put("error_det", errorCode.getDet());
                                        }}
                                        , WsProtocol.EVENT.HT_UNLOCK_SCREEN_FAILED
                                        , ProductionSchedule.STATUS.NG
                                );
                            } catch (Exception e) {
                                Log.e(getString(R.string.tag), e.getMessage());
                            }

                        }
                    }, screen_locked=true);

                    return;
                }

                confirmation("Please select the reason for pending."
                        , getColor(R.color.red)
                        , true
                        , new ActionListenerCallback() {
                            @Override
                            public void onActionSuccess(String successMessage) throws Exception {

                                for (int i=0;i<j_schedules.length();i++) {
                                    JSONObject jobj = j_schedules.getJSONObject(i);
                                    WsClient.sendWsEventLog(StagingActivity_Phase3.this,
                                            new HashMap<String, Object>() {{
                                                put("event_det", successMessage);
//                                                put("schedule_id", jobj.getString("id"));
                                                put("packing_no", str_packing_no);
                                                put("case_no", case_no);
                                                put("pc_no", pc_no);
                                                put("control_no", control_no);
                                                put("part_no", part_no);
                                                put("part_color", part_color);
                                            }}
                                            , WsProtocol.EVENT.HT_STAGING_PENDING
                                            , ProductionSchedule.STATUS.PENDING
                                    );
                                }

                                alertOk("Pending saved.", new ActionListenerCallback() {
                                    @Override
                                    public void onActionSuccess(String successMessage) throws Exception {
                                        reset();
                                    }

                                    @Override
                                    public void onActionFailure(Throwable throwableError) {

                                    }
                                });
                            }

                            @Override
                            public void onActionFailure(Throwable throwableError) {

                            }
                        }, pendingSpinAdapter);
            }
        });

        btn_ng.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Check if no schedule load
                if (j_schedules == null) {
                    return;
                }
                // Open NG dialog
                if (ngSpinAdapter == null) {
                    JSONArray jArray = MainActivity.pendingMasterJsonArray;
                    if (jArray!=null) {

                        try {
                            if (jArray.length() == 0)
                                return;

                            List<PendingMaster> list = new ArrayList<>();
                            for (int i=0;i<jArray.length();i++) {
                                if (jArray.getJSONObject(i).getString("sec").equalsIgnoreCase("ng")) {
                                    String id = jArray.getJSONObject(i).getString("id");
                                    String name = jArray.getJSONObject(i).getString("mesg");

                                    list.add(new PendingMaster(id, name));
                                }
                            }
                            PendingMaster[] pendingMasters = list.toArray(new PendingMaster[0]);

                            Log.d(getString(R.string.tag), Arrays.deepToString(pendingMasters));

                            ngSpinAdapter = new SpinAdapter(
                                    getApplicationContext(), R.layout.spinner_usr_list, pendingMasters);

                        } catch (Exception e) {
                            Log.e(getString(R.string.tag), "ERROR: " + e.getMessage());
                            alertError(e.getMessage(), new ActionListenerCallback() {
                                @Override
                                public void onActionSuccess(String successMessage) throws Exception {

                                }

                                @Override
                                public void onActionFailure(Throwable throwableError) {

                                }
                            }, screen_locked=false);
                        }
                    }
                }

                if (ngSpinAdapter.getCount() == 0) {
                    alertError(ErrorCode.E116.toString(), new ActionListenerCallback() {
                        @Override
                        public void onActionSuccess(String successMessage) throws Exception {

                        }

                        @Override
                        public void onActionFailure(Throwable throwableError) {
                            ErrorCode errorCode = ErrorCode.fromId(Integer.parseInt(throwableError.getMessage()));
                            Toast.makeText(StagingActivity_Phase3.this, errorCode.toString(), Toast.LENGTH_LONG)
                                    .show();
                            try {
                                WsClient.sendWsEventLog(StagingActivity_Phase3.this,
                                        new HashMap<String, Object>() {{
                                            put("event_det", WsProtocol.EVENT.HT_STAGING_NG);
                                            put("error_code", errorCode.getId());
                                            put("error_det", errorCode.getDet());
                                        }}
                                        , WsProtocol.EVENT.HT_UNLOCK_SCREEN_FAILED
                                        , ProductionSchedule.STATUS.NG
                                );
                            } catch (Exception e) {
                                Log.e(getString(R.string.tag), e.getMessage());
                            }
                        }
                    }, screen_locked=true);

                    return;
                }

                confirmation("Please select the reason for NG."
                        , getColor(R.color.red)
                        , true
                        , new ActionListenerCallback() {
                            @Override
                            public void onActionSuccess(String successMessage) throws Exception {

                                for (int i=0;i<j_schedules.length();i++) {
                                    JSONObject jobj = j_schedules.getJSONObject(i);
                                    WsClient.sendWsEventLog(StagingActivity_Phase3.this,
                                            new HashMap<String, Object>() {{
                                                put("event_det", successMessage);
//                                                put("schedule_id", jobj.getString("id"));
                                                put("pc_no", pc_no);
                                                put("control_no", control_no);
                                                put("part_no", part_no);
                                                put("part_color", part_color);
                                                put("case_no", case_no);
                                                put("packing_no", str_packing_no);
                                            }}
                                            , WsProtocol.EVENT.HT_STAGING_NG
                                            , ProductionSchedule.STATUS.NG
                                    );
                                }

                                alertOk("NG saved.", new ActionListenerCallback() {
                                    @Override
                                    public void onActionSuccess(String successMessage) throws Exception {
                                        reset();
                                    }

                                    @Override
                                    public void onActionFailure(Throwable throwableError) {

                                    }
                                });
                            }

                            @Override
                            public void onActionFailure(Throwable throwableError) {

                            }
                        }, ngSpinAdapter);

            }
        });

        btn_answer1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                checkpoint_check(btn_answer1.getText().toString());
            }
        });
        btn_answer2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                checkpoint_check(btn_answer2.getText().toString());
            }
        });
        btn_answer3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                checkpoint_check(btn_answer3.getText().toString());
            }
        });
        btn_answer4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                checkpoint_check(btn_answer4.getText().toString());
            }
        });
    }//onCreate

    private void reset() {
        j_schedules = null;
        matched_schedules = null;
        checkpoint = null;
        total_remaining = 0;
        screen_locked=false;
        waiting_ws_response = false;

        txt_pc_no.setText("");
        txt_part_no.setText("");
        txt_color.setText("");
        txt_maker.setText("");
        txt_control.setText("");
        txt_ttl_qty.setText("");
        txt_chk_point1.setText("");
        txt_chk_point2.setText("");
        txt_chk_point3.setText("");
        txt_chk_point4.setText("");
        content_page2.setVisibility(INVISIBLE);
    }

    @Override
    public void processData(String data, DecodeResult.Result result, String codeType) {
        Log.d(getString(R.string.tag), data);
        if (data.trim().equals("")) {
            Log.e(getString(R.string.tag), "ERROR: data.trim().equals ");
            return;
        }

        if (lbl_tablet_no.getText().toString().trim().equals("")) {
            Log.e(getString(R.string.tag), "ERROR:  "+lbl_tablet_no.getText().toString());
            return;
        }

        if (waiting_ws_response
                && Settings.getMgmtList().get("HT_WAIT_SERVER_RESPONSE").equals("1")
        ) {
            alertOk("Please waiting for server response.", new ActionListenerCallback() {
                @Override
                public void onActionSuccess(String successMessage) {
                }

                @Override
                public void onActionFailure(Throwable throwableError) {

                }
            });
            return;
        }

        if (screen_locked) {
            Log.e(getString(R.string.tag), "ERROR: screen_locked");
            EditText txt_leader_password = (EditText) findViewById(R.id.txt_leader_password);
            txt_leader_password.setEnabled(false);
            txt_leader_password.setText(data);
            Button btn = (Button) findViewById(R.id.popupLayout2_btn1);
            btn.performClick();
            return;
        }

        try {
            Log.d(getString(R.string.tag), String.format("data read[%d bytes]: %s", data.length(), data));

            if (data.length()<143) {
                alertError(ErrorCode.E110.toString(), new ActionListenerCallback() {
                    @Override
                    public void onActionSuccess(String successMessage) throws Exception {

                    }

                    @Override
                    public void onActionFailure(Throwable throwableError) {

                    }
                }, screen_locked=false);
                throw new Exception(ErrorCode.E110.toString());
            }

            part_no = data.substring(0, 29); // 12251-59B -0040   (0043) --> 1225159B 0043 (design part no)
            /**
             * Version < 1.4.8
             *
             part_color = data.substring(59, 66).trim(); // ABCDE
             pc_no = data.substring(66, 81).trim(); // 373-34A-5678-18
             control_no = data.substring(81, 88).trim(); // 149-06

             // v1.4.7
             seq_itm = data.substring(81, 88).trim(); // 149-06 or 030-002

             s_qty = data.substring(88, 95).trim(); // 60

             String recv_date = data.substring(107, 115).trim(); // 01/06/23 -- dd/mm/yy

             // Add supported for PPP
             String model_no = data.substring(115, 118); // Model no
             if (model_no.equals("PPP")) {
             control_no = data.substring(130, 134).trim(); // Use the tail data for control no e.g. XX14
             Log.d(getString(R.string.tag), "Found PPP part change control_no=" + control_no);
             }
             */
            part_color = data.substring(59, 70).trim(); // ABCDE
            pc_no = data.substring(70, 85).trim(); // 373-34A-5678-18
            control_no = data.substring(85, 92).trim(); // 149-06
//            seq_itm = data.substring(85, 92).trim(); // 149-06 or 030-002

            s_qty = data.substring(92, 99).trim(); // 60

            String recv_date = data.substring(111, 119).trim(); // 01/06/23 -- dd/mm/yy

            // Add supported for PPP
            model_no = data.substring(119, 122); // Model no
            if (model_no.equals("PPP")) {
                control_no = data.substring(134, 138).trim(); // Use the tail data for control no e.g. XX14
                case_no = data.substring(85, 88).trim();
                int int_case_no = Integer.parseInt(case_no);
                case_no = String.valueOf(int_case_no);

                str_packing_no = data.substring(89, 92).trim();
                int int_packing_no = Integer.parseInt(str_packing_no);
                str_packing_no = String.valueOf(int_packing_no);

                Log.d(getString(R.string.tag), "Found PPP part change control_no=" + control_no);
            }else {
                model_no = data.substring(134, 138).trim(); //model no
                case_no = "";
                str_packing_no = "";
            }
            Log.d(getString(R.string.tag), "case_no =" + case_no + " str_packing_no"+ str_packing_no);
            // Reformat input
            String p = "([\\d\\w]{5})-([\\d\\w]{3})\\s-[\\d\\w\\-]{4,}\\s+\\(([\\w\\d\\-]{4,})\\).*";
            String[] tmp_ = StringUtil.doScanner(part_no, p);
            Log.d(getString(R.string.tag), String.format("part_no : \"%s\"", part_no));
            Log.d(getString(R.string.tag), Arrays.deepToString(tmp_));
            if (tmp_.length == 3) {
                part_no = String.format("%s%s %s", tmp_[0], tmp_[1], tmp_[2]);
            }
            part_no = part_no.replace("-", "").trim();
            pc_no = pc_no.replace("-", "");

            Log.d(getString(R.string.tag), String.format("%s,%s,%s,%s,%s"
                    , part_no, part_color, pc_no, control_no, s_qty));

            Log.d(getString(R.string.tag), "pc_no "+" = " +pc_no_scan1);
            Log.d(getString(R.string.tag), "control_no "+control_no.substring(0,3)+" = " +control_no_scan1);


            if (pc_no_scan1.trim().equals("") && control_no_scan1.trim().equals("")){
                Log.d(getString(R.string.tag), "all ==''");
                // Get matched schedule from WS
                waiting_ws_response = true;
                WsClient.sendWsEventLog(StagingActivity_Phase3.this,
                        new HashMap<String, Object>() {{
                            put("part_no", part_no);
                            put("part_color", part_color);
                            put("pc_no", pc_no);
                            put("control_no", control_no); // This will match 3 digits left on server side
                            put("recv_date", recv_date);
                            put("packing_no", str_packing_no);
                            put("case_no", case_no);
                            put("event_det", "");

                        }}
                        , WsProtocol.EVENT.HT_STAGING_SCAN_STEP1
                        , ProductionSchedule.STATUS.WORKING
                );

            }else {
                Log.d(getString(R.string.tag), "!=''");
                if (pc_no_scan1.trim().equalsIgnoreCase(pc_no.trim())
                        && control_no_scan1.substring(0,3).trim().equalsIgnoreCase(control_no.substring(0,3).trim())) {
                    Log.d(getString(R.string.tag), "=='' no alert");
                    // Get matched schedule from WS
                    waiting_ws_response = true;
                    WsClient.sendWsEventLog(StagingActivity_Phase3.this,
                            new HashMap<String, Object>() {{
                                put("part_no", part_no);
                                put("part_color", part_color);
                                put("pc_no", pc_no);
                                put("control_no", control_no); // This will match 3 digits left on server side
                                put("recv_date", recv_date);
                                put("packing_no", str_packing_no);
                                put("case_no", case_no);
                                put("event_det", "");

                            }}
                            , WsProtocol.EVENT.HT_STAGING_SCAN_STEP1
                            , ProductionSchedule.STATUS.WORKING
                    );

                }else {
                    Log.d(getString(R.string.tag), "!='' alert");
                    alertError("PC.Lot or Control not match!!", new ActionListenerCallback() {
                        @Override
                        public void onActionSuccess(String successMessage) throws Exception {
                            reset();
                            pc_no_scan1 = "";
                            control_no_scan1 = "";
                        }
                        @Override
                        public void onActionFailure(Throwable throwableError) {

                        }
                    }, screen_locked=true);
                }
            }

            // always hide keyboard after scan
            Utils.hideKeyboardFrom(getApplicationContext(), default_view);

        } catch (Exception e) {
            Log.e(getString(R.string.tag), "ERROR: " + e.getMessage());
            alertError("Please try again!!", new ActionListenerCallback() {
                @Override
                public void onActionSuccess(String successMessage) throws Exception {
                    reset();
                }

                @Override
                public void onActionFailure(Throwable throwableError) {

                }
            }, screen_locked=false);

        }
    }


    @Override
    public void onMessage(WebSocket webSocket, String text) {
        waiting_ws_response = false;

        Log.d(getString(R.string.tag), String.format("%s : received -> \"%s\"", this.getLocalClassName(),
                text));

        runOnUiThread(new Runnable() {

            @Override
            public void run() {

                try {
                    JSONObject jsonObject = new JSONObject(text);
                    JSONObject j_ext;

                    switch (WsProtocol.COMMAND.valueOf(jsonObject.getString("cmd"))) {

                        case HELLO:
                            j_ext = new JSONObject(jsonObject.getString("ext"));
                            WsClient.getInstance().client_id = j_ext.getInt("id");

                            WsClient.sendWs(StagingActivity_Phase3.this,null, WsProtocol.COMMAND.REGISTER_REQUEST);
                            break;

                        case DEVICE_PAIRING_NOTIFY_REQUEST:
                            lbl_tablet_no.setText(jsonObject.getJSONObject("ext").getString("device_id"));

                            WsClient.sendWs(StagingActivity_Phase3.this,null, WsProtocol.COMMAND.DEVICE_PAIRING_NOTIFY_ACK);
                            break;

                        case GET_PAIRED_DEVICE_ACK:
                            lbl_tablet_no.setText("");
                            JSONArray jarray = new JSONArray(jsonObject.getString("ext"));
                            if (jarray.length() > 0) {
                                String tmp = "";
                                for (int i=0; i<jarray.length(); i++) {
                                    tmp = String.format("%s%s%s", tmp, (i>0?",":""), jarray.getJSONObject(i).getString("device_id"));
                                }
                                lbl_tablet_no.setText(tmp);
                            }

                            break;

                        case MEIJI_CARD_READY_REQUEST:

                            WsClient.sendWsEventLog(StagingActivity_Phase3.this,
                                    null
                                    , WsProtocol.EVENT.HT_STAGING_CHECKPOINT
                                    , ProductionSchedule.STATUS.WORKING
                            );

                            if (checkpoint != null) {
                                switch (checkpoint.getString("accept_choice")) {
                                    case "1":
                                        txt_chk_point1.setText(checkpoint.getString("chk_point"));
                                        txt_chk_point2.setText(checkpoint.getString("dummy1"));
                                        txt_chk_point3.setText(checkpoint.getString("dummy2"));
                                        txt_chk_point4.setText(checkpoint.getString("dummy3"));
                                        break;
                                    case "2":
                                        txt_chk_point1.setText(checkpoint.getString("dummy1"));
                                        txt_chk_point2.setText(checkpoint.getString("chk_point"));
                                        txt_chk_point3.setText(checkpoint.getString("dummy2"));
                                        txt_chk_point4.setText(checkpoint.getString("dummy3"));
                                        break;
                                    case "3":
                                        txt_chk_point1.setText(checkpoint.getString("dummy1"));
                                        txt_chk_point2.setText(checkpoint.getString("dummy2"));
                                        txt_chk_point3.setText(checkpoint.getString("chk_point"));
                                        txt_chk_point4.setText(checkpoint.getString("dummy3"));
                                        break;
                                    case "4":
                                        txt_chk_point1.setText(checkpoint.getString("dummy1"));
                                        txt_chk_point2.setText(checkpoint.getString("dummy2"));
                                        txt_chk_point3.setText(checkpoint.getString("dummy3"));
                                        txt_chk_point4.setText(checkpoint.getString("chk_point"));
                                        break;
                                }

//                                content_page1.setVisibility(GONE);
                                content_page2.setVisibility(VISIBLE);
                            } else {
                                // Notify to server
                                for (int i=0;i<j_schedules.length();i++) {
                                    JSONObject jobj = j_schedules.getJSONObject(i);

                                    WsClient.sendWsEventLog(StagingActivity_Phase3.this,
                                            new HashMap<String, Object>() {{
//                                                put("schedule_id", jobj.getString("id"));
                                                put("pc_no", pc_no);
                                                put("control_no", control_no);
                                                put("part_no", part_no);
                                                put("case_no", case_no);
                                                put("packing_no", str_packing_no);
                                                put("part_color", part_color);
                                                put("error_code", E114.getId());
                                                put("error_det", E114.getDet());
                                            }}
                                            , WsProtocol.EVENT.HT_STAGING_CHECKPOINT_FAILED
                                            , ProductionSchedule.STATUS.NG
                                    );
                                }

                                alertError(ErrorCode.E114.toString(), new ActionListenerCallback() {
                                    @Override
                                    public void onActionSuccess(String successMessage) throws Exception {

                                    }

                                    @Override

                                    public void onActionFailure(Throwable throwableError) {
                                        ErrorCode errorCode = ErrorCode.fromId(Integer.parseInt(throwableError.getMessage()));
                                        Toast.makeText(StagingActivity_Phase3.this, errorCode.toString(), Toast.LENGTH_LONG)
                                                .show();
                                        try {
                                            WsClient.sendWsEventLog(StagingActivity_Phase3.this,
                                                    new HashMap<String, Object>() {{
                                                        put("event_det", WsProtocol.EVENT.HT_STAGING_CHECKPOINT_FAILED);
                                                        put("error_code", errorCode.getId());
                                                        put("error_det", errorCode.getDet());
                                                    }}
                                                    , WsProtocol.EVENT.HT_UNLOCK_SCREEN_FAILED
                                                    , ProductionSchedule.STATUS.NG
                                            );
                                        } catch (Exception e) {
                                            Log.e(getString(R.string.tag), e.getMessage());
                                        }
                                    }
                                }, screen_locked=true);
                            }
                            break;

                        case EVENT_LOG_ACK:
                            if (jsonObject.has("ext") && jsonObject.getJSONObject("ext").has("event")) {
                                switch (WsProtocol.EVENT.valueOf(
                                        jsonObject.getJSONObject("ext").getString("event"))) {
                                    case HT_STAGING_SCAN_STEP1_SUCCESS:
                                        j_schedules = new JSONArray(jsonObject.getJSONObject("ext").getString("event_det"));

                                        if (j_schedules.length() > 0) {
                                            JSONObject schedule = j_schedules.getJSONObject(0);
                                            if (!schedule.has("po_no") || schedule.isNull("po_no")) {

                                                for (int i = 0; i < j_schedules.length(); i++) {
                                                    JSONObject jobj = j_schedules.getJSONObject(i);

                                                    WsClient.sendWsEventLog(StagingActivity_Phase3.this,
                                                            new HashMap<String, Object>() {{
//                                                                put("schedule_id", jobj.getString("id"));
                                                                put("pc_no", pc_no);
                                                                put("control_no", control_no);
                                                                put("part_no", part_no);
                                                                put("part_color", part_color);
                                                                put("case_no", case_no);
                                                                put("packing_no", str_packing_no);
                                                                put("error_code", E103.getId());
                                                                put("error_det", E103.getDet());
                                                            }}
                                                            , WsProtocol.EVENT.HT_STAGING_SCAN_STEP1_FAILED
                                                            , ProductionSchedule.STATUS.NG
                                                    );
                                                }
                                            }


                                            // Find total remaining receive
                                            String schedule_id_tmp = "";
                                            for (int i = 0; i < j_schedules.length(); i++) {
                                                total_remaining += j_schedules.getJSONObject(i).getInt("staging_plan_qty")
                                                        - j_schedules.getJSONObject(i).getInt("staging_act_qty");
                                                schedule_id_tmp += (i == 0 ? "" : ",") + j_schedules.getJSONObject(i).getString("id");
                                            }
                                            String maker = j_schedules.getJSONObject(0).getString("maker_code").trim();
//                                            // Update display
                                            txt_pc_no.setText(pc_no);
                                            txt_part_no.setText(part_no);
                                            txt_color.setText(part_color);
                                            txt_control.setText(control_no);
                                            txt_maker.setText(maker);
//                                            txt_ttl_qty.setText(s_qty);
                                            txt_ttl_qty.setText(
                                                    Integer.parseInt(s_qty) < total_remaining ? s_qty :
                                                            String.valueOf(total_remaining)
                                            );
                                            Log.d(getString(R.string.tag), "total_remaining :" + total_remaining);

                                            if (total_remaining == 0) {
                                                alertOk("This job has already finished.", new ActionListenerCallback() {
                                                    @Override
                                                    public void onActionSuccess(String successMessage) throws Exception {
                                                            reset();
                                                    }

                                                    @Override
                                                    public void onActionFailure(Throwable throwableError) {

                                                    }
                                                });
                                            } else {

                                                if (pc_no_scan1.trim().equals("") && control_no_scan1.trim().equals("")) {//remember first tag scan
                                                    pc_no_scan1 = pc_no;
                                                    control_no_scan1 = control_no;
                                                }

                                                Log.d(getString(R.string.tag), "pc_no_scan1 :" + pc_no_scan1);
                                                Log.d(getString(R.string.tag), "control_no_scan1 :" + control_no_scan1);
//
                                                String finalSchedule_id_tmp = schedule_id_tmp;
                                                WsClient.sendWsEventLog(StagingActivity_Phase3.this,
                                                        new HashMap<String, Object>() {{
                                                            put("pc_no", pc_no);
                                                            put("control_no", control_no);
                                                            put("part_no", part_no);
                                                            put("part_color", part_color);
                                                            put("model_no", model_no);
                                                            put("case_no", case_no);
                                                            put("packing_no", str_packing_no);
//                                                        put("schedule_id", finalSchedule_id_tmp);
                                                        }}
                                                        , WsProtocol.EVENT.HT_STAGING_SCAN_STEP1_SUCCESS
                                                        , ProductionSchedule.STATUS.WORKING
                                                );
                                            }
                                        }

                                        break;

                                    case HT_STAGING_SCAN_STEP1_FAILED:

                                        alertError(E108.toString(), new ActionListenerCallback() {
                                            @Override
                                            public void onActionSuccess(String successMessage) throws Exception {

                                            }

                                            @Override
                                            public void onActionFailure(Throwable throwableError) {
                                                ErrorCode errorCode = ErrorCode.fromId(Integer.parseInt(throwableError.getMessage()));
                                                Toast.makeText(StagingActivity_Phase3.this, errorCode.toString(), Toast.LENGTH_LONG)
                                                        .show();
                                                try {
                                                    WsClient.sendWsEventLog(StagingActivity_Phase3.this,
                                                            new HashMap<String, Object>() {{
                                                                put("event_det", WsProtocol.EVENT.HT_STAGING_SCAN_STEP1_FAILED);
                                                                put("error_code", errorCode.getId());
                                                                put("error_det", errorCode.getDet());
                                                            }}
                                                            , WsProtocol.EVENT.HT_UNLOCK_SCREEN_FAILED
                                                            , ProductionSchedule.STATUS.NG
                                                    );
                                                } catch (Exception e) {
                                                    Log.e(getString(R.string.tag), e.getMessage());
                                                }
                                            }
                                        }, screen_locked=true);
                                        throw new Exception(E108.toString());

                                        //break;

                                    case HT_STAGING_CHECKPOINT:
                                        checkpoint = jsonObject.getJSONObject("ext").getJSONObject("event_det");
                                        // random accept choice
                                        int max=4, min=1;
                                        checkpoint.put("accept_choice", String.valueOf(
                                                new Random().nextInt(max - min + 1) + min));
                                        break;

                                    case WB_INVALID_WORKING_STEP:
                                        alertError(E203.toString(), new ActionListenerCallback() {
                                            @Override
                                            public void onActionSuccess(String successMessage) throws Exception {

                                            }

                                            @Override
                                            public void onActionFailure(Throwable throwableError) {
                                            }
                                        }, screen_locked=true);
                                        break;


                                    case WB_CHECKPOINT_DATA_NOT_FOUND:
                                        for (int i=0;i<j_schedules.length();i++) {
                                            JSONObject jobj = j_schedules.getJSONObject(i);

                                            WsClient.sendWsEventLog(StagingActivity_Phase3.this,
                                                    new HashMap<String, Object>() {{
//                                                        put("schedule_id", jobj.getString("id"));
                                                        put("pc_no", pc_no);
                                                        put("control_no", control_no);
                                                        put("part_no", part_no);
                                                        put("part_color", part_color);
                                                        put("case_no", case_no);
                                                        put("packing_no", str_packing_no);
                                                        put("error_code", E114.getId());
                                                        put("error_det", E114.getDet());
                                                    }}
                                                    , WsProtocol.EVENT.HT_STAGING_CHECKPOINT_FAILED
                                                    , ProductionSchedule.STATUS.NG
                                            );
                                        }

                                        alertError(E114.toString(), new ActionListenerCallback() {
                                            @Override
                                            public void onActionSuccess(String successMessage) throws Exception {

                                            }

                                            @Override
                                            public void onActionFailure(Throwable throwableError) {
                                                ErrorCode errorCode = ErrorCode.fromId(Integer.parseInt(throwableError.getMessage()));
                                                Toast.makeText(StagingActivity_Phase3.this, errorCode.toString(), Toast.LENGTH_LONG)
                                                        .show();
                                                try {
                                                    WsClient.sendWsEventLog(StagingActivity_Phase3.this,
                                                            new HashMap<String, Object>() {{
                                                                put("event_det", WsProtocol.EVENT.HT_STAGING_CHECKPOINT_FAILED);
                                                                put("error_code", errorCode.getId());
                                                                put("error_det", errorCode.getDet());
                                                            }}
                                                            , WsProtocol.EVENT.HT_UNLOCK_SCREEN_FAILED
                                                            , ProductionSchedule.STATUS.NG
                                                    );
                                                } catch (Exception e) {
                                                    Log.e(getString(R.string.tag), e.getMessage());
                                                }
                                            }
                                        }, screen_locked=true);
                                        throw new Exception(E114.toString());

                                }
                            }

                            break;
                    }
                } catch (Exception e) {
                    Log.e(getString(R.string.tag), "ERROR: " + e.getMessage());
                    e.printStackTrace();
                }

            }
        });

    }

    private void checkpoint_check(String ans) {
        Log.d(getString(R.string.tag), "check answer: " + ans);
        if (total_remaining == 0) {
            alertOk("This job has already finished.", new ActionListenerCallback() {
                @Override
                public void onActionSuccess(String successMessage) throws Exception {

                }

                @Override
                public void onActionFailure(Throwable throwableError) {

                }
            });
        }

        if (checkpoint != null) {
            try {
                if (ans.equalsIgnoreCase(checkpoint.getString("accept_choice"))) {
                    WsClient.sendWsEventLog(StagingActivity_Phase3.this,
                            new HashMap<String, Object>() {{
                                put("part_no", part_no);
                                put("part_color", part_color);
                                put("pc_no", pc_no);
                                put("control_no", control_no); // This will match 3 digits left on server side
                                put("case_no", case_no);
                                put("packing_no", str_packing_no);

                            }}
                            , WsProtocol.EVENT.HT_STAGING_CHECKPOINT_SUCCESS
                            , ProductionSchedule.STATUS.STAGED
                    );

                    // matched
                    alertOk("matched", new ActionListenerCallback() {
                        @Override
                        public void onActionSuccess(String successMessage) throws Exception {
                                alertOk("staging completed!", new ActionListenerCallback() {
                                    @Override
                                    public void onActionSuccess(String successMessage) throws Exception {
                                        reset();
                                    }

                                    @Override
                                    public void onActionFailure(Throwable throwableError) {

                                    }
                                });
                                Utils.playNotification(getApplicationContext(), RingtoneManager.TYPE_NOTIFICATION);
                        }

                        @Override
                        public void onActionFailure(Throwable throwableError) {

                        }
                    });
                } else {
                    // not match NG
                    alertError("Non-matched\n" + ErrorCode.E105.toString(), new ActionListenerCallback() {
                        @Override
                        public void onActionSuccess(String successMessage) throws Exception {

                        }

                        @Override
                        public void onActionFailure(Throwable throwableError) {
                            ErrorCode errorCode = ErrorCode.fromId(Integer.parseInt(throwableError.getMessage()));
                            Toast.makeText(StagingActivity_Phase3.this, errorCode.toString(), Toast.LENGTH_LONG)
                                    .show();
                            try {
                                WsClient.sendWsEventLog(StagingActivity_Phase3.this,
                                        new HashMap<String, Object>() {{
                                            put("event_det", WsProtocol.EVENT.HT_STAGING_CHECKPOINT_FAILED);
                                            put("error_code", errorCode.getId());
                                            put("error_det", errorCode.getDet());
//                                            put("schedule_id", j_schedules.getJSONObject(0).getDouble("id"));
                                            put("pc_no", pc_no);
                                            put("control_no", control_no);
                                            put("part_no", part_no);
                                            put("part_color", part_color);
                                            put("case_no", case_no);
                                            put("packing_no", str_packing_no);
                                        }}
                                        , WsProtocol.EVENT.HT_UNLOCK_SCREEN_FAILED
                                        , ProductionSchedule.STATUS.NG
                                );
                            } catch (Exception e) {
                                Log.e(getString(R.string.tag), e.getMessage());
                            }
                        }
                    }, screen_locked=true);

                    WsClient.sendWsEventLog(StagingActivity_Phase3.this,
                            new HashMap<String, Object>() {{
                                put("error_code", ErrorCode.E105.getId());
                                put("error_det", ErrorCode.E105.getDet());
//                                put("schedule_id", j_schedules.getJSONObject(0).getDouble("id"));
                                put("pc_no", pc_no);
                                put("control_no", control_no);
                                put("part_no", part_no);
                                put("part_color", part_color);
                                put("case_no", case_no);
                                put("packing_no", str_packing_no);
                            }}
                            , WsProtocol.EVENT.HT_STAGING_CHECKPOINT_FAILED
                            , ProductionSchedule.STATUS.NG
                    );
                }
            } catch (Exception e) {
                Log.e(getString(R.string.tag), "ERROR: " + e.getMessage());
                alertError(e.getMessage(), new ActionListenerCallback() {
                    @Override
                    public void onActionSuccess(String successMessage) throws Exception {

                    }

                    @Override
                    public void onActionFailure(Throwable throwableError) {

                    }
                }, screen_locked=false);
            }
        } else {
            alertError(ErrorCode.E114.toString(), new ActionListenerCallback() {
                @Override
                public void onActionSuccess(String successMessage) throws Exception {

                }

                @Override
                public void onActionFailure(Throwable throwableError) {
                    ErrorCode errorCode = ErrorCode.fromId(Integer.parseInt(throwableError.getMessage()));
                    Toast.makeText(StagingActivity_Phase3.this, errorCode.toString(), Toast.LENGTH_LONG)
                            .show();
                    try {
                        WsClient.sendWsEventLog(StagingActivity_Phase3.this,
                                new HashMap<String, Object>() {{
                                    put("event_det", WsProtocol.EVENT.HT_STAGING_CHECKPOINT_FAILED);
                                    put("error_code", errorCode.getId());
                                    put("error_det", errorCode.getDet());
//                                    put("schedule_id", j_schedules.getJSONObject(0).getDouble("id"));
                                    put("pc_no", pc_no);
                                    put("control_no", control_no);
                                    put("part_no", part_no);
                                    put("part_color", part_color);
                                    put("case_no", case_no);
                                    put("packing_no", str_packing_no);
                                }}
                                , WsProtocol.EVENT.HT_UNLOCK_SCREEN_FAILED
                                , ProductionSchedule.STATUS.NG
                        );
                    } catch (Exception e) {
                        Log.e(getString(R.string.tag), e.getMessage());
                    }
                }
            }, screen_locked=true);
        }
    }

    private void confirmation(String msg, int color, boolean isBtnOkShow
            , ActionListenerCallback callback, SpinAdapter spinAdapter) {


        Log.d(getString(R.string.tag), "confirmation() " + msg);

        RelativeLayout layout = popupLayout1;
        TextView lbl_msg = (TextView) findViewById(R.id.popupLayout1_txt);
        Button btnOk = (Button) findViewById(R.id.popupLayout1_btn1);
        Button btnConfirm = (Button) findViewById(R.id.popupLayout1_btn2);
        Spinner ddl_options = (Spinner) findViewById(R.id.ddl_options);

        ddl_options.setVisibility (spinAdapter == null ? GONE : VISIBLE);

        if (spinAdapter != null) {
            ddl_options.setAdapter(spinAdapter);
        }

        lbl_msg.setText(msg);
        lbl_msg.setTextColor(color);
        btnOk.setVisibility(isBtnOkShow ? VISIBLE : INVISIBLE);
        layout.setVisibility(VISIBLE);
        btnOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    layout.setVisibility(GONE);
                    callback.onActionFailure(null);
                } catch (Exception e) {
                    // In case if item is the top most view
                };
            }
        });
        btnConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    layout.setVisibility(GONE);
                    callback.onActionSuccess(
                            spinAdapter.getItem(
                                    ddl_options.getSelectedItemPosition()
                            ).getName()
                    );
                } catch (Exception e) {
                    // In case if item is the top most view
                };
            }
        });

    }

    private void alertOk(String msg, ActionListenerCallback callback) {
        // Enable the ENT key down, it must current focus on multiline text input
        default_view.requestFocus();

        RelativeLayout layout = popupLayout2;
        TextView lbl_msg = (TextView) findViewById(R.id.popupLayout2_txt);
        Button btn = (Button) findViewById(R.id.popupLayout2_btn1);
        EditText txt_leader_password = (EditText) findViewById(R.id.txt_leader_password);
        txt_leader_password.setEnabled(false);

        lbl_msg.setText(msg);
        lbl_msg.setTextColor(getColor(R.color.black));
        layout.setVisibility(VISIBLE);
        txt_leader_password.setVisibility(GONE);
        btn.setBackgroundColor(getColor(R.color.green));
        btn.setTextColor(getColor(R.color.white));
        btn.setText("OK [ENT]");
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.d(getString(R.string.tag), "onClick() alertOK" );
                // stop activity
                try {
                    layout.setVisibility(GONE);
                    callback.onActionSuccess("");
                } catch (Exception e) {
                    // In case if item is the top most view
                };
            }
        });

    }

    private void alertError(String msg, ActionListenerCallback callback, Boolean isLockScreen) {
        alertError(msg, callback, isLockScreen, R.string.LEVEL_PERMIT_UNLOCK_SCREEN);
    }

    private void alertError(String msg, ActionListenerCallback callback, Boolean isLockScreen, int level_permit) {
        // Enable the ENT key down, it must current focus on multiline text input
        default_view.requestFocus();

        RelativeLayout layout = popupLayout2;
        TextView lbl_msg = (TextView) findViewById(R.id.popupLayout2_txt);
        Button btn = (Button) findViewById(R.id.popupLayout2_btn1);
        EditText txt_leader_password = (EditText) findViewById(R.id.txt_leader_password);
        txt_leader_password.setEnabled(false);

        if (isLockScreen) {
            txt_leader_password.setVisibility(VISIBLE);
            txt_leader_password.setText("");

            Utils.playMedia(getApplicationContext(), R.raw.ship_siren);
        } else {
            txt_leader_password.setVisibility(GONE);
            Utils.playTones(ToneGenerator.TONE_CDMA_ABBR_ALERT, 10000, 900);
        }

        lbl_msg.setText(msg);
        lbl_msg.setTextColor(getColor(R.color.red));
        layout.setVisibility(VISIBLE);
        btn.setBackgroundColor(getColor(R.color.red));
        btn.setTextColor(getColor(R.color.white));
        btn.setText("NG [" + (isLockScreen?"scan":"ENT") + "]");
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.d(getString(R.string.tag), "onClick() alertError" );
                // stop activity
                try {
                    if (!isLockScreen) {
                        layout.setVisibility(GONE);
                        callback.onActionSuccess("");
                    } else {
                        // check password
                        if (!Settings.getMgmtList().containsKey(getString(level_permit))) {
                            callback.onActionFailure(new Exception(String.valueOf(E111.getId())));
                            return;
                        }

                        List<String> levelTokens = Arrays.asList(Settings.getMgmtList().get(getString(level_permit))
                                .split(getString(R.string.DELIMITER_SETTINGS)));
                        EditText txt_leader_password = (EditText) findViewById(R.id.txt_leader_password);
                        txt_leader_password.setEnabled(false);
                        if (!MainActivity.instance.userHashMap.containsKey(txt_leader_password.getText().toString())) {
                            callback.onActionFailure(new Exception(String.valueOf(E112.getId())));
                            return;
                        }

                        User user = MainActivity.instance.userHashMap.get(txt_leader_password.getText().toString());
                        if (levelTokens.contains(user.getLevel())) {
                            screen_locked = false;
                            layout.setVisibility(GONE);
                            callback.onActionSuccess("");
                        } else {
                            callback.onActionFailure(new Exception(String.valueOf(E122.getId())));
                        }
                    }

                } catch (Exception e) {
                    // In case if item is the top most view
                };
            }
        });

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onFinished(String result) {

    }

    @Override
    public String getJobId() {
        return null;
    }

    @Override
    public String getStage() {
        return stage.toString();
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        Log.d(getString(R.string.tag), String.format("keyCode: %d", keyCode) );
        if (keyCode >= KeyMapping.P1.getId()
                && keyCode <= KeyMapping.P4.getId())
        {
            if (popupLayout1.getVisibility() == VISIBLE) {
                Button btnOk = (Button) findViewById(R.id.popupLayout1_btn1);
                Button btnConfirm = (Button) findViewById(R.id.popupLayout1_btn2);
                switch (KeyMapping.fromId(keyCode)) {
                    case P1:
                        btnOk.performClick();
                        break;

                    case P2:
                        btnConfirm.performClick();
                        break;

                }
            } else {
                switch (KeyMapping.fromId(keyCode)) {
                    case P1:
                        btn_main_menu.performClick();
                        break;

                    case P2:
                        btn_clear.performClick();
                        break;

                    case P3:
                        btn_pending.performClick();
                        break;

                    case P4:
                        btn_ng.performClick();
                        break;

                }
            }
        } else if (keyCode == KeyMapping.ENT.getId()) {
            if (popupLayout2.getVisibility() == VISIBLE) {
                Button btn = (Button) findViewById(R.id.popupLayout2_btn1);
                btn.requestFocus();
                btn.performClick();
            }
            return false;
        }

        return super.onKeyUp(keyCode, event);
    }

    @Override
    public void onBackPressed() {

    }

}