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.E110;
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 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.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 com.tomastc.anickd.R;
import com.tomastc.anickd.lib.ProductionSchedule;

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

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

import okhttp3.WebSocket;

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

    private String job_id; // Random hash 32
    private Button btn_main_menu, btn_clear, btn_pending, btn_ng
            , btn_answer1, btn_answer2, btn_answer3, btn_answer4;
    private EditText txt_pc_no, txt_part_no, txt_part_color, txt_control_no, txt_qty;
    private TextView txt_chk_point1, txt_chk_point2, txt_chk_point3, txt_chk_point4, lbl_tablet_no
            , lbl_open_meiji_card;
    private RelativeLayout content_page1, content_page2, popupLayout1, popupLayout2;
    private SpinAdapter pendingSpinAdapter=null, ngSpinAdapter=null;

    private int scan_step = 0;
    private boolean waiting_ws_response = false;
    private boolean screen_locked = false;

    private ProductionSchedule.STAGE stage = ProductionSchedule.STAGE.RECEIVING;

    private String s_qty, part_no, part_color, pc_no, control_no
            // v1.4.7
            , seq_itm;

    private JSONArray j_schedules, matched_schedules;
    private JSONObject checkpoint;
    private int total_remaining = 0, total_received = 0;
    private String step1_event_id = "";

    @Override
    public void processData(String data, DecodeResult.Result result, String codeType) {

        //if (waiting_ws_response) {
        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) {
            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));

            switch (scan_step) {
                /**
                 * Remove out this step, operator will scan tag receive at 1st step
                case 0:
                    // Format: NO[2] + PO_NO[12] + QTY[7]
                    // Length: 21
                    // Other: all digits
                    if (data.length()!=21 || !StringConvert.isDigit(data)) {
                        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());
                    }

                    po_no = data.substring(2,14);
                    s_qty = data.substring(14);

                    Log.d(getString(R.string.tag), "PO NO: " + po_no);
                    Log.d(getString(R.string.tag), "QTY: " + s_qty);

                    // Get schedule from PO_NO
                    j_ext = new JSONObject();
                    j_ext.put("user_id", Settings.getLoginUser().getId());
                    j_ext.put("device_id", Settings.getDeviceNo());
                    j_ext.put("device_type", getString(R.string.device_type));
                    j_ext.put("job_id", job_id);
                    j_ext.put("po_no", po_no);
                    j_ext.put("event", WsProtocol.EVENT.HT_RECEIVING_SCAN_STEP1);
                    j_ext.put("status", ProductionSchedule.STATUS.WORKING);
                    j_ext.put("stage", stage);
                    WsClient.getInstance().sendMessage(
                            WsProtocol.encapsulation(
                                    WsProtocol.COMMAND.EVENT_LOG_REQUEST.toString(),
                                    j_ext
                            )
                    );
                    waiting_ws_response = true;

                    Toast.makeText(ReceivingActivity.this, "Scan data OK.", Toast.LENGTH_LONG)
                            .show();

                    break;

                case 1:

                 */
                case 0:
                    // Format: PART_NO[29] + PART_NAME[30] + PART_COLOR[7] + PC_NO[15] + CONTROL_NO[7] + QTY[7]
                    // Length: 143
                    // Other:

                    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
                    String 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
                        Log.d(getString(R.string.tag), "Found PPP part change control_no=" + control_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));

                    // Get matched schedule from WS
                    waiting_ws_response = true;
                    WsClient.sendWsEventLog(ReceivingActivity.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("qty", s_qty);
                                put("recv_date", recv_date);
                                // v1.4.7
                                put("seq_itm", seq_itm);
                            }}
                            , WsProtocol.EVENT.HT_RECEIVING_SCAN_STEP1
                            , ProductionSchedule.STATUS.WORKING
                    );

                    break;
            }

            // 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 {

                }

                @Override
                public void onActionFailure(Throwable throwableError) {

                }
            }, screen_locked=false);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_receiving);

        default_view = (EditText) findViewById(R.id.txt_tmp);

        // update MessageListener class
        WsClient.getInstance().setOnMessageListener(this);

        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);
        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);

        txt_pc_no = (EditText) findViewById(R.id.txt_pc_no);
        txt_part_no = (EditText) findViewById(R.id.txt_part_no);
        txt_part_color = (EditText) findViewById(R.id.txt_part_color);
        txt_control_no = (EditText) findViewById(R.id.txt_control_no);
        txt_qty = (EditText) findViewById(R.id.txt_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);
        lbl_open_meiji_card = (TextView) findViewById(R.id.lbl_open_meiji_card);

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

        reset();

        try {
            // Set AREA
            WsClient.sendWs(ReceivingActivity.this, new HashMap<String, Object>() {{
                put("area", ProductionSchedule.AREA.RECEIVING);
            }}, WsProtocol.COMMAND.SET_AREA_REQUEST);

            // Get paired tablet device id
            WsClient.sendWs(ReceivingActivity.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(ReceivingActivity.this, errorCode.toString(), Toast.LENGTH_LONG)
                                    .show();
                            try {
                                WsClient.sendWsEventLog(ReceivingActivity.this,
                                        new HashMap<String, Object>() {{
                                            put("event_det", WsProtocol.EVENT.HT_RECEIVING_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(ReceivingActivity.this,
                                            new HashMap<String, Object>() {{
                                                put("event_det", successMessage);
                                                put("schedule_id", jobj.getString("id"));
                                            }}
                                            , WsProtocol.EVENT.HT_RECEIVING_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(ReceivingActivity.this, errorCode.toString(), Toast.LENGTH_LONG)
                                    .show();
                            try {
                                WsClient.sendWsEventLog(ReceivingActivity.this,
                                        new HashMap<String, Object>() {{
                                            put("event_det", WsProtocol.EVENT.HT_RECEIVING_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(ReceivingActivity.this,
                                            new HashMap<String, Object>() {{
                                                put("event_det", successMessage);
                                                put("schedule_id", jobj.getString("id"));
                                            }}
                                            , WsProtocol.EVENT.HT_RECEIVING_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());
            }
        });
    }

    private void checkpoint_check(String ans) {
        // Not function while it is already finished
        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) {

                }
            });
        }

        Log.d(getString(R.string.tag), "check answer: " + ans);
        if (checkpoint != null) {
            try {
                if (ans.equalsIgnoreCase(checkpoint.getString("accept_choice"))) {

                    // Find schedule_id and qty
                    int i_receive = Integer.parseInt(txt_qty.getText().toString());
                    if (i_receive <= 0) {
                        alertError("The receive qty should be more than zero."
                                , new ActionListenerCallback() {
                                    @Override
                                    public void onActionSuccess(String successMessage) throws Exception {
                                        txt_qty.requestFocus();
                                    }

                                    @Override
                                    public void onActionFailure(Throwable throwableError) {

                                    }
                                }, screen_locked=false);
                        return;
                    }
                    if (i_receive > total_remaining) {
                        alertError(String.format("The receive number is exceed the remaining[%d].", total_remaining)
                                , new ActionListenerCallback() {
                            @Override
                            public void onActionSuccess(String successMessage) throws Exception {
                                txt_qty.requestFocus();
                            }

                            @Override
                            public void onActionFailure(Throwable throwableError) {

                            }
                        }, screen_locked=false);
                        return;
                    }
                    if (matched_schedules == null) {
                        matched_schedules = new JSONArray();
                    }
                    for (int i=0;i<j_schedules.length();i++) {
                        JSONObject jsonObject = j_schedules.getJSONObject(i);
                        int able_to_receive = jsonObject.getInt("receive_plan_qty")
                                - jsonObject.getInt("receive_act_qty");
                        if (able_to_receive == 0) { // skip received job
                            continue;
                        }
                        if (i_receive > able_to_receive) {
                            jsonObject.put("receive_act_qty",
                                    jsonObject.getInt("receive_act_qty")
                                + able_to_receive
                            );
                            i_receive -= able_to_receive;
                            matched_schedules.put(jsonObject);
                        } else {
                            jsonObject.put("receive_act_qty",
                                    jsonObject.getInt("receive_act_qty")
                                            + i_receive
                            );
                            matched_schedules.put(jsonObject);
                            break;
                        }
                    }
                    WsClient.sendWsEventLog(ReceivingActivity.this,
                            new HashMap<String, Object>() {{
                                put("schedules", matched_schedules);
                                put("step1_event_id", step1_event_id);

                                // v1.4.6: Stamp schedule ID to event log for HT_RECEIVING_CHECKPOINT_SUCCESS
                                put("schedule_id", matched_schedules.getJSONObject(0).getDouble("id"));
                            }}
                            , WsProtocol.EVENT.HT_RECEIVING_CHECKPOINT_SUCCESS
                            , ProductionSchedule.STATUS.RECEIVED
                    );

                    // matched
                    alertOk("matched", new ActionListenerCallback() {
                        @Override
                        public void onActionSuccess(String successMessage) throws Exception {
                            if (total_remaining == Integer.parseInt(txt_qty.getText().toString())) {
                                alertOk("All items receive completed!", new ActionListenerCallback() {
                                    @Override
                                    public void onActionSuccess(String successMessage) throws Exception {
                                        reset();
                                    }

                                    @Override
                                    public void onActionFailure(Throwable throwableError) {

                                    }
                                });
                                Utils.playNotification(getApplicationContext(), RingtoneManager.TYPE_NOTIFICATION);
                            } else {
                                reset();
                            }
                        }

                        @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(ReceivingActivity.this, errorCode.toString(), Toast.LENGTH_LONG)
                                    .show();
                            try {
                                WsClient.sendWsEventLog(ReceivingActivity.this,
                                        new HashMap<String, Object>() {{
                                            put("event_det", WsProtocol.EVENT.HT_RECEIVING_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);

                    WsClient.sendWsEventLog(ReceivingActivity.this,
                            new HashMap<String, Object>() {{
                                put("error_code", ErrorCode.E105.getId());
                                put("error_det", ErrorCode.E105.getDet());
                            }}
                            , WsProtocol.EVENT.HT_RECEIVING_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(ReceivingActivity.this, errorCode.toString(), Toast.LENGTH_LONG)
                            .show();
                    try {
                        WsClient.sendWsEventLog(ReceivingActivity.this,
                                new HashMap<String, Object>() {{
                                    put("event_det", WsProtocol.EVENT.HT_RECEIVING_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);
        }
    }

    private void reset() {
        job_id = StringConvert.randomHex(32);
        scan_step = 0;
        j_schedules = null;
        matched_schedules = null;
        checkpoint = null;
        total_remaining = 0;
        total_received = 0;
        step1_event_id = "";

        waiting_ws_response = false;

        txt_pc_no.setText("");
        txt_part_no.setText("");
        txt_part_color.setText("");
        txt_control_no.setText("");
        txt_qty.setText("");
        txt_chk_point1.setText("");
        txt_chk_point2.setText("");
        txt_chk_point3.setText("");
        txt_chk_point4.setText("");

        content_page1.setVisibility(VISIBLE);
        content_page2.setVisibility(INVISIBLE);
        lbl_open_meiji_card.setVisibility(INVISIBLE);
    }

    @Override
    public void onFinished(String result) {

    }

    @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(ReceivingActivity.this,null, WsProtocol.COMMAND.REGISTER_REQUEST);
                            break;

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

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

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

                            break;

                        case MEIJI_CARD_READY_REQUEST:

                            WsClient.sendWsEventLog(ReceivingActivity.this,
                                    null
                                    , WsProtocol.EVENT.HT_RECEIVING_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(ReceivingActivity.this,
                                            new HashMap<String, Object>() {{
                                                put("schedule_id", jobj.getString("id"));
                                                put("error_code", E114.getId());
                                                put("error_det", E114.getDet());
                                            }}
                                            , WsProtocol.EVENT.HT_RECEIVING_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(ReceivingActivity.this, errorCode.toString(), Toast.LENGTH_LONG)
                                                .show();
                                        try {
                                            WsClient.sendWsEventLog(ReceivingActivity.this,
                                                    new HashMap<String, Object>() {{
                                                        put("event_det", WsProtocol.EVENT.HT_RECEIVING_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_RECEIVING_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(ReceivingActivity.this,
                                                            new HashMap<String, Object>() {{
                                                                put("schedule_id", jobj.getString("id"));
                                                                put("error_code", E103.getId());
                                                                put("error_det", E103.getDet());
                                                            }}
                                                            , WsProtocol.EVENT.HT_RECEIVING_SCAN_STEP1_FAILED
                                                            , ProductionSchedule.STATUS.NG
                                                    );
                                                }

                                                alertError(E103.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(ReceivingActivity.this, errorCode.toString(), Toast.LENGTH_LONG)
                                                                .show();
                                                        try {
                                                            WsClient.sendWsEventLog(ReceivingActivity.this,
                                                                    new HashMap<String, Object>() {{
                                                                        put("event_det", WsProtocol.EVENT.HT_RECEIVING_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(E103.toString());
                                            }

                                            String model_no = "";
                                            if (schedule.has("model_no")) {
                                                model_no = schedule.getString("model_no");
                                            }


                                            // Find total remaining receive
                                            String schedule_id_tmp = "";
                                            for (int i=0;i<j_schedules.length();i++) {
                                                total_remaining += j_schedules.getJSONObject(i).getInt("receive_plan_qty")
                                                        - j_schedules.getJSONObject(i).getInt("receive_act_qty");
                                                total_received += j_schedules.getJSONObject(i).getInt("receive_act_qty");
                                                schedule_id_tmp += (i==0 ? "" : ",") + j_schedules.getJSONObject(i).getString("id");
                                            }


                                            // Update display
                                            txt_pc_no.setText(pc_no);
                                            txt_part_no.setText(part_no);
                                            txt_part_color.setText(part_color);
                                            txt_control_no.setText(control_no);
                                            txt_qty.setText(
                                                    Integer.parseInt(s_qty) < total_remaining ? s_qty :
                                                    String.valueOf(total_remaining)
                                            );

                                            lbl_open_meiji_card.setVisibility(VISIBLE);

                                            String finalSchedule_id_tmp = schedule_id_tmp;
                                            String finalModel_no = model_no;
                                            WsClient.sendWsEventLog(ReceivingActivity.this,
                                                    new HashMap<String, Object>() {{
                                                        put("part_no", part_no);
                                                        put("part_color", part_color);
                                                        put("model_no", finalModel_no);
                                                        put("schedule_id", finalSchedule_id_tmp);
                                                    }}
                                                    , WsProtocol.EVENT.HT_RECEIVING_SCAN_STEP1_SUCCESS
                                                    , ProductionSchedule.STATUS.WORKING
                                            );
                                        }
                                        break;

                                    case WB_INVALID_CUTPART:
                                        alertError(E124.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(ReceivingActivity.this, errorCode.toString(), Toast.LENGTH_LONG)
                                                        .show();
                                                try {
                                                    WsClient.sendWsEventLog(ReceivingActivity.this,
                                                            new HashMap<String, Object>() {{
                                                                put("event_det", WsProtocol.EVENT.HT_RECEIVING_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);
                                        break;

                                    case HT_RECEIVING_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(ReceivingActivity.this, errorCode.toString(), Toast.LENGTH_LONG)
                                                        .show();
                                                try {
                                                    WsClient.sendWsEventLog(ReceivingActivity.this,
                                                            new HashMap<String, Object>() {{
                                                                put("event_det", WsProtocol.EVENT.HT_RECEIVING_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_RECEIVING_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));

                                        // keep step 1 event id
                                        step1_event_id = jsonObject.getJSONObject("ext").getString("step1_event_id");

                                        break;


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

                                            WsClient.sendWsEventLog(ReceivingActivity.this,
                                                    new HashMap<String, Object>() {{
                                                        put("schedule_id", jobj.getString("id"));
                                                        put("error_code", E114.getId());
                                                        put("error_det", E114.getDet());
                                                    }}
                                                    , WsProtocol.EVENT.HT_RECEIVING_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(ReceivingActivity.this, errorCode.toString(), Toast.LENGTH_LONG)
                                                        .show();
                                                try {
                                                    WsClient.sendWsEventLog(ReceivingActivity.this,
                                                            new HashMap<String, Object>() {{
                                                                put("event_det", WsProtocol.EVENT.HT_RECEIVING_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();
                }

            }
        });

    }

    @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;
        }
        else if (keyCode >= 8 && keyCode <= 11) {
            if (!txt_qty.isFocused()
                    && content_page2.getVisibility() == VISIBLE) {
                checkpoint_check(String.valueOf(keyCode - 7));
            }
        }

        return super.onKeyUp(keyCode, event);
    }


    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) {
                // 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) {
                // 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
    public String getJobId() {
        return job_id;
    }

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

    @Override
    public void onBackPressed() {

    }
}