package com.tomastc.anickd;

import static android.view.View.GONE;
import static android.view.View.VISIBLE;
import static com.tomastc.anickd.lib.ErrorCode.E111;
import static com.tomastc.anickd.lib.ErrorCode.E112;
import static com.tomastc.anickd.lib.ErrorCode.E122;

import android.content.Context;
import android.graphics.Color;
import android.media.ToneGenerator;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

import androidx.constraintlayout.widget.ConstraintLayout;

import com.keyence.autoid.sdk.scan.DecodeResult;
import com.tomastc.anickd.lib.ActionListenerCallback;
import com.tomastc.anickd.lib.AlertProgress;
import com.tomastc.anickd.lib.CkdInterface;
import com.tomastc.anickd.lib.ErrorCode;
import com.tomastc.anickd.lib.KeyMapping;
import com.tomastc.anickd.lib.ProductionSchedule;
import com.tomastc.anickd.lib.Scanner;
import com.tomastc.anickd.lib.Settings;
import com.tomastc.anickd.lib.TagMaker;
import com.tomastc.anickd.lib.User;
import com.tomastc.anickd.lib.common.AsyncTcpClient;
import com.tomastc.anickd.lib.common.CallbackListener;
import com.tomastc.anickd.lib.common.MessageListener;
import com.tomastc.anickd.lib.common.ScrollToTrick;
import com.tomastc.anickd.lib.common.StringUtil;
import com.tomastc.anickd.lib.common.Utils;

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

import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import cn.pedant.SweetAlert.SweetAlertDialog;
import okhttp3.WebSocket;

public class PrintTagActivity extends Scanner implements View.OnClickListener, CallbackListener, MessageListener, CkdInterface {
    TextView txt_header, lbl_tablet_no;
    private ScrollView scr_contents;
    private TableLayout tbl_contents_label_scan;
    String str_mode, content_label, KeyLabelSelect;
    int Reprint_act_qty;
    Map<String, TagMaker> map_label;
    AlertProgress alert;
    ConstraintLayout layout_menu, layout_scan;
    Button btn_clear, btn_print;
    private RelativeLayout popupLayout2;
    private boolean screen_locked = false;
    private boolean waiting_ws_response = false;
    boolean printing_label;
    private ProductionSchedule.STAGE stage = ProductionSchedule.STAGE.LABELING;
    private JSONArray j_schedules;
    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_print_tag);
        default_view = (EditText) findViewById(R.id.txt_label_issue_tmp);

        WsClient.getInstance().setOnMessageListener(this);

        str_mode = "";
        content_label = "";
        KeyLabelSelect = "";
        printing_label = false;
        map_label = new LinkedHashMap<>();
        alert = new AlertProgress(PrintTagActivity.this);

        layout_scan = (ConstraintLayout)findViewById(R.id.layout_scan);
        layout_menu = (ConstraintLayout)findViewById(R.id.layout_menu);
        popupLayout2 = (RelativeLayout) findViewById(R.id.popupLayout2);
        scr_contents = (ScrollView) findViewById(R.id.scr_contents);
        tbl_contents_label_scan = (TableLayout)findViewById(R.id.tbl_contents_label_scan);

        txt_header = (TextView) findViewById(R.id.layout_menu_title);
        txt_header.setText("Print tag");
        lbl_tablet_no = (TextView) findViewById(R.id.lbl_tablet_no);
        btn_print = (Button) findViewById(R.id.btn_print);
        btn_clear = (Button) findViewById(R.id.btn_clear);

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_tag_receive:
                content_label = "TAG-RECEIVE";
                Set_Mode("Tag Receive");
                break;

            case R.id.btn_tem_tag:
                content_label = "TAG-MAKER";
                Set_Mode("Tag  Maker");
                break;

            case R.id.btn_main_menu:
                finish();
                break;

            case R.id.btn_clear:
                Reset_layout();
                break;

            case R.id.btn_print:
                if (printing_label == false) {
                    printing_label = true;
                    Click_Print();
                }
                break;
        }
    }

    private void Click_Print() {
        if (j_schedules.length() == 0)
            return;

        if (Settings.getMgmtList().get("SKIP_PRINT").trim().equals("1")) {
            AlertConfirmPrint(false);

        } else {
            if (Settings.getPrinter().trim().equals("")
                    ||Settings.getPrinter().trim().equals(null)
                    ||Settings.getPrinter().trim().equals("null")){
                printing_label = false;
                new SweetAlertDialog(PrintTagActivity.this, SweetAlertDialog.WARNING_TYPE)
                        .setTitleText("WARNING")
                        .setContentText("Please setting printer")
                        .show();
            }else {
                Print_Label();
            }
        }
    }

    private void Set_Mode(String mode) {
        layout_menu.setVisibility(View.GONE);
        layout_scan.setVisibility(View.VISIBLE);
        btn_print.setVisibility(View.VISIBLE);
        btn_clear.setVisibility(View.VISIBLE);
        str_mode = mode;
        txt_header.setText("Print "+str_mode);


        if (str_mode.trim().equals("Tag Receive")){
            try {
                WsClient.sendWsEventLog(PrintTagActivity.this,
                        null
                        , WsProtocol.EVENT.HT_PRINT_TAG_RECEIVE_OPEN
                        , ProductionSchedule.STATUS.WORKING
                );
            } catch (Exception e) {
                Log.e(getString(R.string.tag), e.getMessage());
            }
        }else {
            try {
                WsClient.sendWsEventLog(PrintTagActivity.this,
                        null
                        , WsProtocol.EVENT.HT_PRINT_TEMPORARY_TAG_OPEN
                        , ProductionSchedule.STATUS.WORKING
                );
            } catch (Exception e) {
                Log.e(getString(R.string.tag), e.getMessage());
            }
        }
    }


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

        if (content_label.trim().equals(""))
            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) {
            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 {
            if (str_mode.trim().equals("Tag Receive")) {//Mode: Tag Receive | scan: delivery sheet
                if (data.length() == 21) {//scan delivery sheet
                    String order_no = data.substring(2, 14);
                    Log.e(getString(R.string.tag), order_no);
                    try {
                        waiting_ws_response = true;
                        WsClient.sendWsEventLog(this,
                                new HashMap<String, Object>() {{
                                    put("order_no", order_no);
                                    put("event_det", "");
                                }}
                                , WsProtocol.EVENT.HT_PRINT_TAG_RECEIVE_SCAN_STEP1
                                , ProductionSchedule.STATUS.WORKING
                        );
                    } catch (Exception e) {
                        Log.e(getString(R.string.tag), e.getMessage());
                        e.printStackTrace();
                    }

                } else {
                    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());
                }
            }else {//Mode: Tag Maker | scan: Tag Receive
                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)
                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
                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("-", "");
                case_no = case_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));

                try {
                    waiting_ws_response = true;
                    WsClient.sendWsEventLog(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);
                                put("packing_no", str_packing_no);
                                put("case_no", case_no);
                                put("event_det", "");
                            }}
                            , WsProtocol.EVENT.HT_PRINT_TEMPORARY_TAG_SCAN_STEP1
                            , ProductionSchedule.STATUS.WORKING
                    );
                } catch (Exception e) {
                    Log.e(getString(R.string.tag), e.getMessage());
                    e.printStackTrace();
                }

            }

            Utils.hideKeyboardFrom(getApplicationContext(), default_view);
        } catch (Exception e) {
            Log.e(getString(R.string.tag), "ERROR: " + e.getMessage());
        }
    }

    private void Print_Label() {
        alert.setMessage("           Printing label....         ");
        alert.show();

        String tmp_label = "";
        try {
            for (int i = 0; i < j_schedules.length(); i++) {
                String payload = j_schedules.getJSONObject(i).getString("payload");
                String model_no = j_schedules.getJSONObject(i).getString("model_no");

                String[] payload2 = payload.split("\\|");
                Log.e(getString(R.string.tag), "payload: " + payload2[20]);
                Log.e(getString(R.string.tag), "payload digit: " + payload2[20].length());

                if (str_mode.trim().equals("Tag Receive")) {
                    model_no = model_no.trim().equals("PPP") ? "-PBP" : "";//if model_no == PPP != ""  TAG-RECEIVE only |TEMPORARY-TAG = ""
                } else {
                    model_no = "";
                }
                String tmp = String.format(
                        "%s %s-%s%s\n%s"
                        , "PST"
                        , Settings.getPrinter()
                        , content_label
                        , model_no
                        , payload+"\n");

                tmp_label = (tmp_label + tmp);

                Log.e(getString(R.string.tag), "payload tmp: " + tmp);
            }
            Log.e(getString(R.string.tag), "payload tmp_label: " + tmp_label);

            String err_msg = "";
            try {
                err_msg = "Server connection failed!\nPlease contact leader.";

                new AsyncTcpClient(getApplicationContext(),
                        Settings.getMgmtList().get("lpc_host"),
                        Integer.parseInt(Settings.getMgmtList().get("lpc_port")),
                        tmp_label+"\n\n\n"
                ) {
                    @Override
                    protected void onFinished(String response) {
                        Log.d(getString(R.string.tag), "TCP response: " + response);

                        if (response.equals("OK")) {
                                alert.dismiss();
                                AlertConfirmPrint(false);

                        } else {
                            printing_label = false;
                            alert.dismiss();
                            alertError("Can't connect to print server", new ActionListenerCallback() {
                                @Override
                                public void onActionSuccess(String successMessage) throws Exception {

                                }
                                @Override
                                public void onActionFailure(Throwable throwableError) {

                                }
                            }, screen_locked=false);
                        }
                    }
                }.execute();
                throw new JSONException(err_msg);

            } catch (JSONException e) {
                printing_label = false;
                Log.e(getString(R.string.tag), "ERROR: " + e.getMessage());
            }

        }catch (JSONException e){
            printing_label = false;
            Log.e(getString(R.string.tag), "ERROR: " + e.getMessage());
        }
    }

    private void AlertConfirmPrint(boolean select_label) {
            new SweetAlertDialog(PrintTagActivity.this, SweetAlertDialog.SUCCESS_TYPE)
                    .setTitleText("SUCCESS")
                    .setContentText("Click 'No' if nothing printed out?")
                    .setCancelText("No")
                    .showCancelButton(true)
                    .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sDialog) {
                            sDialog.dismiss();
                        }
                    })
                    .setConfirmText("Yes")
                    .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sDialog) {
                            sDialog.dismiss();
                            if (select_label == true){
                                Confirm_Select_Label();
                            }else {
                                Confirm_Label();
                            }
                        }
                    })
                    .show();
    }


    private void Confirm_Label() {
        WsProtocol.EVENT event = null;
        if (str_mode.trim().equals("Tag Receive")) {
            if (Reprint_act_qty == 0) {
                event = WsProtocol.EVENT.HT_PRINT_TAG_RECEIVE_SCAN_STEP1_SUCCESS;
            } else {
                event = WsProtocol.EVENT.HT_REPRINT_TAG_RECEIVE_LEADER_CONFIRM_SUCCESS;
            }
        }else {
            event = WsProtocol.EVENT.HT_PRINT_TEMPORARY_TAG_SCAN_STEP1_SUCCESS;
        }
        try {
                for (int i = 0; i < j_schedules.length(); i++) {
                    String schedule_id = j_schedules.getJSONObject(i).getString("id").trim();
                    WsClient.sendWsEventLog(PrintTagActivity.this,
                            new HashMap<String, Object>() {{
                                put("schedule_id", schedule_id);
                                put("event_det", "");
                                put("printer", Settings.getPrinter());
                            }}
                            , event
                            , ProductionSchedule.STATUS.COMPLETED
                    );
                }

            } catch (Exception e) {
            printing_label = false;
            alertError(e.getMessage(), new ActionListenerCallback() {
                @Override
                public void onActionSuccess(String successMessage) throws Exception {

                }

                @Override
                public void onActionFailure(Throwable throwableError) {

                }
            }, screen_locked=false);
        }
    }

    private void Confirm_Select_Label() {
        try {
            Log.d(getString(R.string.tag), "Key = "+KeyLabelSelect);
                WsClient.sendWsEventLog(PrintTagActivity.this,
                        new HashMap<String, Object>() {{
                            put("schedule_id", KeyLabelSelect);
                            put("event_det", "");
                            put("printer", Settings.getPrinter());
                        }}
                        , WsProtocol.EVENT.HT_PRINT_TEMPORARY_TAG_SCAN_STEP1_SUCCESS
                        , ProductionSchedule.STATUS.COMPLETED
                );
        } catch (Exception e) {
            printing_label = false;
            alertError(e.getMessage(), new ActionListenerCallback() {
                @Override
                public void onActionSuccess(String successMessage) throws Exception {

                }

                @Override
                public void onActionFailure(Throwable throwableError) {

                }
            }, screen_locked=false);
        }
    }
    private void Reset_layout() {
        map_label.clear();
        j_schedules = null;
        printing_label = false;
        waiting_ws_response = false;
        KeyLabelSelect = "";
        tbl_contents_label_scan.removeAllViews();

    }

    private void redrawTable(String scroll_to_item) {
        Log.d(getString(R.string.tag), "redrawStockFifo() called");
        Log.d(getString(R.string.tag), "j_schedules"+j_schedules.length());

        TableRow scroll_to_row = null;

        try {
            Context context = getApplicationContext();

            tbl_contents_label_scan.removeAllViews();

            int colorYellow = Color.argb(0xff, 0xff, 0xff, 0x00);
            int colorGreen = Color.argb(0xff, 0x00, 0xff, 0x00);
            int colorRed = Color.argb(0xff, 0xff, 0x00, 0x00);
            int colorBlack = Color.argb(0xff, 0x00, 0x00, 0x00);
            int colorWhite = Color.argb(0xff, 0xff, 0xff, 0xff);

//            for (int i = 0; i < j_schedules.length(); i++) {
            int i = 0;
            for (String key : map_label.keySet()) {

                TagMaker item = map_label.get(key);

                int bgColor = Color.argb((i % 2) == 0 ? 0x30 : 0x10, 0xaa, 0xaa, 0xaa);
                int bgColorStatus = bgColor;
                int textColor = colorBlack;

                String model_no = item.getModel_no();
                String control_no = item.getControl_no();
                if (model_no.trim().equals("PPP")){
                    control_no = control_no.substring(0,4);
                }else {
                    control_no = control_no.substring(0,3);
                }
//                String ttl_qty = j_schedules.getJSONObject(i).getString("lbl_ttl_qty");


                TableRow tableRow = new TableRow(context);
                TableRow.LayoutParams layoutParams = new TableRow.LayoutParams(
                        TableLayout.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT);
                layoutParams.setMargins(1, 1, 1, 1);
                tableRow.setLayoutParams(layoutParams);

                int width = 300;
                int col_height = 40;
                int[] col_width = {20, 26, 20, 15, 19};

                TextView textView = new TextView(context);
                textView.setText(item.getPc_no());
                textView.setWidth(width * col_width[0] / 100);
                textView.setHeight(col_height);
                textView.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
                textView.setBackgroundColor(bgColor);
                textView.setTextColor(textColor);
                textView.setPadding(1, 5, 0, 0);
                textView.setLayoutParams(layoutParams);
                tableRow.addView(textView);

                textView = new TextView(context);
                textView.setText(item.getPart_no());
                textView.setWidth(width * col_width[1] / 100);
                textView.setHeight(col_height);
                textView.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
                textView.setBackgroundColor(bgColor);
                textView.setTextColor(textColor);
                textView.setPadding(1, 5, 0, 0);
                textView.setLayoutParams(layoutParams);
                tableRow.addView(textView);

                textView = new TextView(context);
                textView.setText(item.getPart_color());
                textView.setWidth(width * col_width[2] / 100);
                textView.setHeight(col_height);
                textView.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
                textView.setBackgroundColor(bgColor);
                textView.setTextColor(textColor);
                textView.setPadding(1, 5, 0, 0);
                textView.setLayoutParams(layoutParams);
                tableRow.addView(textView);

                textView = new TextView(context);
                textView.setText(control_no);
                textView.setWidth(width * col_width[3] / 100);
                textView.setHeight(col_height);
                textView.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
                textView.setBackgroundColor(bgColor);
                textView.setTextColor(textColor);
                textView.setSingleLine(false);
                textView.setPadding(1, 5, 0, 0);
                textView.setLayoutParams(layoutParams);
                tableRow.addView(textView);

                textView = new TextView(context);
                textView.setText(item.getLbl_ttl_qty());
                textView.setWidth(width * col_width[4] / 100);
                textView.setHeight(col_height);
                textView.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
                textView.setBackgroundColor(bgColorStatus);
                textView.setTextColor(textColor);
                textView.setPadding(1, 5, 0, 0);
                textView.setLayoutParams(layoutParams);
                tableRow.addView(textView);

                tbl_contents_label_scan.addView(tableRow);

                if (content_label.trim().equals("TAG-MAKER")) {
                    tableRow.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Log.e(getString(R.string.tag), "click: " + item.getId());
                            Alert_Change_Qty(item.getId(),item.getLbl_ttl_qty());

                        }
                    });
                }

            }

            // scroll to last item added
            if (scroll_to_row != null)
                scr_contents.post(new ScrollToTrick(scr_contents, scroll_to_row));
        } catch (Exception e) {
            alertError(e.getMessage(), new ActionListenerCallback() {
                @Override
                public void onActionSuccess(String successMessage) throws Exception {

                }

                @Override
                public void onActionFailure(Throwable throwableError) {

                }
            }, screen_locked=false);
            e.printStackTrace();
        }
    }

    private void Alert_Change_Qty(String key, String qty) {
        KeyLabelSelect = key;
        Log.e(getString(R.string.tag), KeyLabelSelect+ " | " + qty);
        final EditText editText = new EditText(PrintTagActivity.this);
        editText.setBackgroundResource(R.drawable.img_background);
        editText.setGravity(Gravity.CENTER);
        editText.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL);
        editText.setTextSize(20);
        int colorBlack = Color.argb(0xff, 0x00, 0x00, 0x00);
        int colorgray = Color.argb(0x55, 0x00, 0x00, 0x00);
        editText.setTextColor(colorBlack);
        editText.setHint(qty);
        editText.setHintTextColor(colorgray);

        SweetAlertDialog dialog = new SweetAlertDialog(PrintTagActivity.this, SweetAlertDialog.NORMAL_TYPE)
                .setTitleText("Change qty")
                .setCancelText("Cancel")
                .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sDialog) {
                        KeyLabelSelect = "";
                        sDialog.dismiss();
                    }
                })
                .setConfirmText("Print")
                .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sDialog) {
                        sDialog.dismiss();
                        if (editText.getText().toString().trim().equals(""))
                            return;
                        TagMaker item = map_label.get(KeyLabelSelect);

                        String payload = item.getPayload();
                        Log.e(getString(R.string.tag), "old payload: " + payload);

                        String[] arry = payload.split("\\|");
                        arry[8] = editText.getText().toString().trim();
//
                        StringBuilder sb = new StringBuilder();
                        for (int i = 0; i < arry.length; i++) {
                            sb.append(arry[i]);
                            if (i != arry.length - 1) {
                                sb.append("|");
                            }
                        }

                        Log.e(getString(R.string.tag), "new payload: " + sb);

                        item.setPayload(sb.toString());
                        map_label.put(KeyLabelSelect,item);
                        Print_Label_select(KeyLabelSelect);

                    }
                });
        dialog.setCustomView(editText);
        dialog.show();
    }

    private void Print_Label_select(String key) {
        alert.setMessage("           Printing label....         ");
        alert.show();

                TagMaker label = map_label.get(key);
                String payload = label.getPayload();

                String tmp = String.format(
                        "%s %s-%s%s\n%s"
                        , "PST"
                        , Settings.getPrinter()
                        , content_label
                        , ""
                        , payload+"\n");

            String err_msg = "";
            try {
                err_msg = "Server connection failed!\nPlease contact leader.";


                new AsyncTcpClient(getApplicationContext(),
                        Settings.getMgmtList().get("lpc_host"),
                        Integer.parseInt(Settings.getMgmtList().get("lpc_port")),
                        tmp+"\n\n\n"
                ) {
                    @Override
                    protected void onFinished(String response) {
                        Log.d(getString(R.string.tag), "TCP response: " + response);

                        if (response.equals("OK")) {
                            alert.dismiss();
                            AlertConfirmPrint(true);

                        } else {
                            printing_label = false;
                            alert.dismiss();
                            alertError("Can't connect to print server", new ActionListenerCallback() {
                                @Override
                                public void onActionSuccess(String successMessage) throws Exception {

                                }
                                @Override
                                public void onActionFailure(Throwable throwableError) {

                                }
                            }, screen_locked=false);
                        }
                    }
                }.execute();
                throw new JSONException(err_msg);

            } catch (JSONException e) {
                printing_label = false;
                Log.e(getString(R.string.tag), "ERROR: " + e.getMessage());
            }
    }

    @Override
    public void onMessage(WebSocket webSocket, String text) {

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

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

                            WsClient.sendWs(PrintTagActivity.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 EVENT_LOG_ACK:
                            if (jsonObject.has("ext") && jsonObject.getJSONObject("ext").has("event")) {
                                switch (WsProtocol.EVENT.valueOf(
                                        jsonObject.getJSONObject("ext").getString("event"))) {
                                    case HT_PRINT_TAG_RECEIVE_SCAN_STEP1_SUCCESS:
                                        map_label.clear();
                                        j_schedules = new JSONArray(jsonObject.getJSONObject("ext").getString("event_det"));
                                        for (int i = 0; i < j_schedules.length(); i++) {
                                            map_label.put(j_schedules.getJSONObject(i).getString("id").trim(), new TagMaker(
                                                    j_schedules.getJSONObject(i).getString("id").trim(),
                                                    j_schedules.getJSONObject(i).getString("pc_no").trim(),
                                                    j_schedules.getJSONObject(i).getString("part_no").trim(),
                                                    j_schedules.getJSONObject(i).getString("part_color").trim(),
                                                    j_schedules.getJSONObject(i).getString("control_no").trim(),
                                                    j_schedules.getJSONObject(i).getString("lbl_ttl_qty").trim(),
                                                    j_schedules.getJSONObject(i).getString("model_no").trim(),
                                                    j_schedules.getJSONObject(i).getString("action_act_qty").trim(),
                                                    j_schedules.getJSONObject(i).getString("status").trim(),
                                                    j_schedules.getJSONObject(i).getString("payload")));

                                            String[] payload = j_schedules.getJSONObject(i).getString("payload").split("\\|");
                                            Log.e(getString(R.string.tag), "payload: " + payload[20]);
                                            Log.e(getString(R.string.tag), "payload digit: " + payload[20].length());


                                        }

                                        Reprint_act_qty = j_schedules.getJSONObject(0).getInt("action_act_qty");
                                        if (Reprint_act_qty > 0){//0 = new, >0 = reprint
                                            //alert learder
                                            alertError("Error", new ActionListenerCallback() {
                                                @Override
                                                public void onActionSuccess(String successMessage) throws Exception {
                                                    Print_Label();
                                                }

                                                @Override
                                                public void onActionFailure(Throwable throwableError) {

                                                }
                                            }, screen_locked=true);
                                        }
//                                     //view data
                                        redrawTable(null);
                                        break;

                                    case HT_PRINT_TAG_RECEIVE_SCAN_STEP1_FAILED:
//                                        alertError("Tag receive not found", new ActionListenerCallback() {
                                        alertError("Tag receive Print manual", new ActionListenerCallback() {
                                            @Override
                                            public void onActionSuccess(String successMessage) throws Exception {

                                            }

                                            @Override
                                            public void onActionFailure(Throwable throwableError) {

                                            }
                                        }, screen_locked=false);
                                        Reset_layout();
                                        break;

                                    case HT_PRINT_TEMPORARY_TAG_SCAN_STEP1_SUCCESS:
                                        map_label.clear();
                                        j_schedules = new JSONArray(jsonObject.getJSONObject("ext").getString("event_det"));
                                        for (int i = 0; i < j_schedules.length(); i++) {
                                            map_label.put(j_schedules.getJSONObject(i).getString("id").trim(), new TagMaker(
                                                    j_schedules.getJSONObject(i).getString("id").trim(),
                                                    j_schedules.getJSONObject(i).getString("pc_no").trim(),
                                                    j_schedules.getJSONObject(i).getString("part_no").trim(),
                                                    j_schedules.getJSONObject(i).getString("part_color").trim(),
                                                    j_schedules.getJSONObject(i).getString("control_no").trim(),
                                                    j_schedules.getJSONObject(i).getString("lbl_ttl_qty").trim(),
                                                    j_schedules.getJSONObject(i).getString("model_no").trim(),
                                                    j_schedules.getJSONObject(i).getString("action_act_qty").trim(),
                                                    j_schedules.getJSONObject(i).getString("status").trim(),
                                                    j_schedules.getJSONObject(i).getString("payload")));
                                        }

                                        redrawTable(null);
                                        break;

                                    case HT_PRINT_TEMPORARY_TAG_SCAN_STEP1_FAILED:
                                    case HT_PRINT_TEMPORARY_TAG_SCAN_STEP1_SUCCESS_ACK:
                                    case HT_REPRINT_TAG_RECEIVE_LEADER_CONFIRM_SUCCESS_ACK:
                                    case HT_PRINT_TAG_RECEIVE_SCAN_STEP1_SUCCESS_ACK:
                                        Reset_layout();
                                        break;
                                }
                            }
                            break;
                    }
                } catch (Exception e) {
                    Log.e(getString(R.string.tag), "ERROR: " + e.getMessage());
                    e.printStackTrace();
                }
            }
        });

    }

    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,
                R.color.red, R.color.red, R.color.white, "NG");
    }

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

        RelativeLayout layout = popupLayout2;
        RelativeLayout alert_layout = (RelativeLayout)findViewById(R.id.layout_alert);
        TextView lbl_msg = (TextView) findViewById(R.id.popupLayout2_txt);
        TextView msg_reprint = (TextView)findViewById(R.id.popupLayout2_txt_reprint);
        TextView msg_howto = (TextView)findViewById(R.id.popupLayout2_txt_reprint2);
        Button btn = (Button) findViewById(R.id.popupLayout2_btn1);
        Button btn_cancel = (Button) findViewById(R.id.popupLayout2_cancel);
        EditText txt_leader_password = (EditText) findViewById(R.id.txt_leader_password);
        txt_leader_password.setEnabled(false);


        if (isLockScreen) {
            btn.setBackgroundColor(getColor(R.color.btn_background));
            lbl_msg.setTextColor(getColor(R.color.white));
            alert_layout.setBackground(getDrawable(R.drawable.background_reprint));
            msg_reprint.setVisibility(VISIBLE);
            msg_howto.setVisibility(VISIBLE);
            txt_leader_password.setVisibility(VISIBLE);
            txt_leader_password.setText("");
            btn_cancel.setVisibility(VISIBLE);
            btn.setText("Re-Print");

            if (btn_prefix.equalsIgnoreCase("NG"))
                Utils.playMedia(getApplicationContext(), R.raw.ship_siren);
        } else {
            lbl_msg.setTextColor(getColor(txt_color));
            btn.setBackgroundColor(getColor(btn_bg_color));
            alert_layout.setBackground(getDrawable(R.drawable.background_border));
            txt_leader_password.setVisibility(GONE);
            btn_cancel.setVisibility(GONE);
            msg_reprint.setVisibility(GONE);
            msg_howto.setVisibility(GONE);
            btn.setText("ENT");
            Utils.playTones(ToneGenerator.TONE_CDMA_ABBR_ALERT, 10000, 900);
        }

        lbl_msg.setText(msg);

        layout.setVisibility(VISIBLE);
        btn_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    screen_locked = false;
                    layout.setVisibility(GONE);
                    Reset_layout();
                } catch (Exception e) {
                    // In case if item is the top most view
                };
            }
        });

        btn.setTextColor(getColor(btn_txt_color));
//        btn.setText(btn_prefix + " [" + (isLockScreen?"Re-Print":"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(txt_leader_password.getText().toString());

                        } 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 null;
    }

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

    }

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

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode >= KeyMapping.P1.getId()
                && keyCode <= KeyMapping.P4.getId())
        {
            switch (KeyMapping.fromId(keyCode)) {
                case P1:
                    finish();
                    break;

                case P2:
                    if (str_mode.trim().equals("")){
                        content_label = "TAG-RECEIVE";
                        Set_Mode("Tag Receive");
                    }else {
                        Reset_layout();
                    }
                    break;
                case P3:
                    if (str_mode.trim().equals("")){
                        content_label = "TAG-MAKER";
                        Set_Mode("Tag  Maker");
                    }
                    break;
                case P4:
                    if (printing_label == false) {
                        printing_label = true;
                        Click_Print();
                    }
                    break;
            }
        }

        return super.onKeyUp(keyCode, event);
    }

    @Override
    public void onBackPressed() {

    }
}