package com.tomas.ht_mast;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.graphics.Color;
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.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

import com.keyence.autoid.sdk.scan.DecodeResult;
import com.tomas.ht_mast.ListData.Payload_list;
import com.tomas.ht_mast.lib.AlertProgress;
import com.tomas.ht_mast.lib.KeyMapping;
import com.tomas.ht_mast.lib.Scanner;
import com.tomas.ht_mast.lib.Settings;
import com.tomas.ht_mast.lib.common.AsyncHttpClient;
import com.tomas.ht_mast.lib.common.AsyncTcpClient;
import com.tomas.ht_mast.lib.common.ScrollToTrick;
import com.tomas.ht_mast.lib.common.Utils;

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

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.stream.Collectors;

import cn.pedant.SweetAlert.SweetAlertDialog;

public class OutboutManualRecheck_Activity extends Scanner implements View.OnClickListener {
    Calendar calendar;
    SimpleDateFormat date;
    TextView txt_user, txt_device, txt_date, txt_part_no, txt_part_name, txt_total;
    Button btn_clear, btn_confirm;
    String str_today,  t_order, t_part, t_dwg, t_lot_no, t_qty, t_rank, t_box ;;
    boolean b_confirm, manual_total;
    JSONObject label, repack_label;
    DecimalFormat decimalFormat;
    Map<String, JSONObject> label_scan;
    Map<String, Payload_list>map_payload;
    List<Payload_list> payload_label, payload_repack, payload_print;
    List<Integer> sending_ticket;
    Double act_scan_qty = 0.0, total_change = 0.0;
    Double plan_qty = 0.0;
    TableLayout tbl_stock_fifo;
    ScrollView scr_contents;
    AlertProgress alert;
    Integer LABEL_QTY, PRINT_TIMES;
    private volatile boolean stopThread = true;
    Comparator<JSONObject> comparator = (JSONObject o1, JSONObject o2) -> {
        try {
            return o1.getInt("seq_no") - o2.getInt("seq_no");
        } catch (Exception e) {
            return 0;
        }
    };

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

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

        label_scan = new LinkedHashMap<>();
        map_payload = new LinkedHashMap<>();
        payload_label = new ArrayList<Payload_list>();
        payload_repack = new ArrayList<Payload_list>();
        payload_print = new ArrayList<Payload_list>();

        sending_ticket = new ArrayList<>();
        sending_ticket.add(0,1);//for send outbound
        sending_ticket.add(1,1);//for sent inbound
        sending_ticket.add(2, 1);//for sent outbound repack

        act_scan_qty = 0.0;
        plan_qty = 0.0;
        manual_total = false;
        b_confirm = false;
        repack_label = null;
        decimalFormat = new DecimalFormat("#,#00");
        alert = new AlertProgress(OutboutManualRecheck_Activity.this);

        calendar = Calendar.getInstance();
        date = new SimpleDateFormat("dd/MM/yyyy");
        str_today = date.format(calendar.getTime());

        txt_user = (TextView) findViewById(R.id.txt_user);
        txt_user.setText("User : "+ Settings.getLoginUser().getName());
        txt_device = (TextView) findViewById(R.id.txt_device);
        txt_device.setText("Device : "+Settings.getDeviceNo());
        txt_date = (TextView) findViewById(R.id.txt_date);
        txt_date.setText(str_today);

        txt_part_no = (TextView) findViewById(R.id.txt_part_no);
        txt_part_name = (TextView) findViewById(R.id.txt_part_name);
        txt_total = (TextView) findViewById(R.id.txt_total);
        txt_total.setInputType(InputType.TYPE_NULL);
        txt_total.setFocusableInTouchMode(false);
        txt_total.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (act_scan_qty > 0) {
                    Alert_Change_Plan_Qty("Change Total Qty.");
                }else {
                    Alert_Change_Plan_Qty("Enter Plan Qty.");
                }
            }
        });

        btn_clear = (Button)findViewById(R.id.btn_clear);
        btn_confirm = (Button)findViewById(R.id.btn_confirm);

        tbl_stock_fifo = (TableLayout) findViewById(R.id.tbl_stock_fifo);
        scr_contents = (ScrollView) findViewById(R.id.scr_contents);


    }

    private void Alert_Change_Plan_Qty(String msg) {
        final EditText editText = new EditText(OutboutManualRecheck_Activity.this);
        editText.setBackgroundResource(R.drawable.img_background);
        editText.setGravity(Gravity.CENTER);
        editText.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_NUMBER_FLAG_SIGNED);
        editText.setTextSize(20);
        editText.setHint(String.format("%.2f",plan_qty));

        SweetAlertDialog dialog = new SweetAlertDialog(OutboutManualRecheck_Activity.this, SweetAlertDialog.NORMAL_TYPE)
                .setTitleText(msg)
                .setCancelText("Cancel")
                .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sDialog) {
                        sDialog.dismiss();
                    }
                })
                .setConfirmText("OK")
                .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sDialog) {
                        sDialog.dismiss();

                        if (label_scan.size() > 0){ //have list label
                            new SweetAlertDialog(OutboutManualRecheck_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("WARNING")
                                    .setContentText("Click \"Yes\" to confirm change plan qty!")
                                    .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();
                                            try {
                                                if (editText.getText().toString().trim().equals(""))
                                                    return;

                                                manual_total = true;
                                                total_change = Double.parseDouble(editText.getText().toString().trim());
                                                plan_qty = total_change;

                                                Log.d(getString(R.string.tag), "Check:" + act_scan_qty + " | " + plan_qty);
                                                if (act_scan_qty > plan_qty) {
                                                    label_scan = checkList(label_scan, plan_qty, manual_total);

                                                }
                                                redrawStockFifo(null);
                                            }
                                            catch(Exception err)
                                            {
                                                new SweetAlertDialog(OutboutManualRecheck_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                                        .setTitleText("WARNING")
                                                        .setContentText("Format is wrong!")
                                                        .show();
                                                editText.setText("");

                                            }
                                        }
                                    })
                                    .show();

                        }else {
                            try {
                                manual_total = true;
                                total_change = Double.parseDouble(editText.getText().toString().trim());
                                plan_qty = total_change;
                                redrawStockFifo(null);
                            }catch (Exception err) {
                                new SweetAlertDialog(OutboutManualRecheck_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                        .setTitleText("WARNING")
                                        .setContentText("Format is wrong!")
                                        .show();
                                editText.setText("");

                            }
                        }
                    }


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

    Map<String, JSONObject> checkList(Map<String, JSONObject> alist, Double manual_qty, boolean isManual) {
        if (!isManual)
            return alist;

        Double sum_qty = 0.0;
        HashMap<String, JSONObject> tmpList = new HashMap<>();
        for (Map.Entry<String, JSONObject> entry : alist.entrySet()) {
            String key = entry.getKey();
            JSONObject value = entry.getValue();
            tmpList.put(key, value);


            try {
                sum_qty += value.getDouble("act_stock_qty");
                Log.d(getString(R.string.tag), "sum_qty:" + sum_qty+"/"+manual_qty);

                if (sum_qty >= manual_qty)
                    break;

            }catch (JSONException e){
                Log.e("MAST","ERROR: " + e.getMessage());
            }
        }
        return tmpList;
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.imb_back:
                finish();
                break;

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

            case R.id.btn_confirm:
                if (b_confirm == false) {
                    Block_button();
                    Check_Total();
                }
                break;
        }
    }



    @Override
    public void processData(String data, DecodeResult.Result result, String codeType) {
        if(data.trim().equals(""))
            return;

        try {
            Log.d(getString(R.string.tag), "data read:" + data);
            String[] tokens = data.split(getString(R.string.DELIMITER_SCAN_TOKEN), -1);
            Log.d(getString(R.string.tag), Arrays.deepToString(tokens));

            if (tokens.length == 7){
                t_order = tokens[0].trim();
                t_part = tokens[1].trim();
                t_dwg = tokens[2].trim();
                t_lot_no = tokens[3].trim();
                t_qty = tokens[4].trim();
                t_rank = tokens[5].trim();
                t_box = tokens[6].trim();//key of label

                if (label_scan.size() > 0){
                    Log.e(getString(R.string.tag), "scan: " + t_part.substring(4).trim()+"|"+txt_part_no.getText().toString().trim().substring(4));
                    if (t_part.substring(4).trim().contains(txt_part_no.getText().toString().trim().substring(4))){
                        Check_label();

                    }else {
                        showWarning("Part No. not match!!");
                    }
                }else {
                    Check_label();
                }
            }else {
                showWarning("Invalid QR Code!!");
            }
            Utils.hideKeyboardFrom(getApplicationContext(), default_view);

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

    static JSONObject getLastEntry(Map<String, JSONObject> alist) {
        final Set<Map.Entry<String, JSONObject>> mapValues = alist.entrySet();
        final int len = mapValues.size();
        final Map.Entry<String, JSONObject>[] test = new Map.Entry[len];
        mapValues.toArray(test);
        System.out.println("Key=" + test[len - 1].getKey() + ", Value=" + test[len - 1].getValue());

        return test[len - 1].getValue();
    }

    private void Check_Total() {
        Log.d(getString(R.string.tag), "Check:" + act_scan_qty+" | "+plan_qty);
        if (act_scan_qty > plan_qty){
            Double dif = (act_scan_qty - plan_qty);
            repack_label = getLastEntry(label_scan);
            try {
                repack_label.put("pick_qty", repack_label.getDouble("act_stock_qty") - dif);
                Issue_RepackLabel(repack_label, repack_label.getDouble("act_stock_qty") - dif);

            }catch (JSONException e){

            }

        }else {
            SendOutbound();
        }
    }

    private void Clear_layout() {
        Unblock_button();
        repack_label = null;
        manual_total = false;
        act_scan_qty = 0.0;
        plan_qty = 0.0;
        label_scan.clear();
        txt_part_name.setText("");
        txt_part_no.setText("");
        redrawStockFifo(null);

    }

    private void Check_label() {
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "LABEL/DETAIL");
            json.put("order_no", t_order);
            json.put("parts_no", t_part);
            json.put("lot_no", t_lot_no);
            json.put("serial_no", t_box);

            new AsyncHttpClient(getApplicationContext(),
                    Settings.getMgmtList().get("web_api") + "/ht_api.php",
                    json.toString()) {
                @Override
                protected void onFinished(String response, int resp_code) {
                    Log.d(getString(R.string.tag), "response: " + response);

                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        String value = jsonObject.getString("value");
                        JSONArray jArray = new JSONArray(value);

                        if (jArray.length() == 0){
                            showWarning("Label not found!!");
                        }else {

                            label = jArray.getJSONObject(0);
                            String key_map = label.getString("id");
                            Log.d(getString(R.string.tag), "key_map: "+key_map);

                            // Check label status
                            if (label.getInt("status") != 2) {
                                showWarning("Invalid Label Status!!");
                                return;
                            }

//                            check Duplicated
                            if (label_scan.containsKey(key_map)) {
                                showWarning("Duplicated scan Label!!");
                                return;
                            }

                            if (label_scan.size() == 0){
                                txt_part_no.setText(label.getString("lbl_part_no").trim());
                                txt_part_name.setText(label.getString("lbl_part_name").trim());
                            }

                            Log.d(getString(R.string.tag), "manual_total: "+ String.valueOf(manual_total));
                                label.put("repack_flag", "0");
                                label.put("label_id", label.getString("id"));
                                label.put("seq_no", String.valueOf(label_scan.size() + 1));
                                label_scan.put( key_map, label);
//                            }


                            redrawStockFifo(null);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }.execute();

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void redrawStockFifo(String scroll_to_item) {

        Log.d(getString(R.string.tag), "redrawStockFifo() called");

        TableRow scroll_to_row = null;

        try {
            Context context = getApplicationContext();

            // clear tbl_serial_scan
            tbl_stock_fifo.removeAllViews();

            int i = 0;
            act_scan_qty = 0.0;

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

            SortedSet<JSONObject> items = new TreeSet<>(comparator);
            items.addAll(label_scan.values());
            for (JSONObject item : label_scan.values()) {

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

                //JSONObject item = mapItems.get(key);
                String id = item.getString("seq_no");
                String lot_no = item.getString("lot_no");
                String location_id = item.getString("last_location_id");
                String box = item.getString("serial_no");
                String qty = item.getString("act_stock_qty");
                String unit = item.getString("control_unit").trim();

//                String status = "OK";
//                bgColorStatus = colorGreen;

                Log.d(getString(R.string.tag), "stock_fifo: "+id+"|"+ lot_no+"|"+location_id+"|"+qty);
                act_scan_qty = (act_scan_qty +item.getDouble("act_stock_qty"));
                Log.d(getString(R.string.tag), "act_plan_qty: "+act_scan_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 = {10, 90, 20, 25, 60, 20};

                TextView textView = new TextView(context);
                textView.setText(id);
                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(lot_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(location_id);
                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(box);
                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(qty);
                textView.setWidth(width * col_width[4] / 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(unit);
                textView.setWidth(width * col_width[5] / 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_stock_fifo.addView(tableRow);

                if (scroll_to_item == null) { // latest schedule is auto focus
                    scroll_to_row = tableRow;
                } else if (item.getString("id").equalsIgnoreCase(scroll_to_item)) {
                    scroll_to_row = tableRow;
                }
            }

            if (manual_total == false ){
                plan_qty = act_scan_qty;
            }else {
                plan_qty = total_change;
            }

            txt_total.setText(String.format("%.2f/%.2f",act_scan_qty,plan_qty));

            // scroll to last item added
            if (scroll_to_row != null)
                scr_contents.post(new ScrollToTrick(scr_contents, scroll_to_row));
        } catch (Exception e) {
            Log.e(getString(R.string.tag), e.getMessage());
            e.printStackTrace();
        }
    }


    private void Issue_RepackLabel(JSONObject master_label, Double repack_qty) {
        payload_label.clear();
        payload_repack.clear();
        try {
            Log.d(getString(R.string.tag), "Issue_RepackLabel: " + master_label.getString("id").trim() + "/ "+repack_qty);

            JSONObject json = new JSONObject();
            json.put("cmd", "RELABELING/CONFIRM/PREPARE");
            json.put("ref_label_id", master_label.getString("label_id").trim());
            json.put("new_qty", repack_qty);
            json.put("user_id",Settings.getLoginUser().getId());

            new AsyncHttpClient(getApplicationContext(),
                    Settings.getMgmtList().get("web_api") + "/ht_api.php",
                    json.toString()) {
                @Override
                protected void onFinished(String response, int resp_code) {
                    Log.d(getString(R.string.tag), "response: " + response);

                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        String status = jsonObject.getString("status");

                        if (status.equals("success")) {
                            String value = jsonObject.getString("value");
                            JSONArray jArray = new JSONArray(value);

                            for (int i = 0; i < jArray.length(); i++) {
                                String  scrap_flg =  jArray.getJSONObject(i).getString("scrap_flg").trim();
                                if(scrap_flg.trim().equals("1")){
                                    scrap_flg =  "-SC";
                                }else {
                                    scrap_flg =  "";
                                }

                                map_payload.put(String.valueOf(i), new Payload_list(
                                        jArray.getJSONObject(i).getString("id"),
                                        scrap_flg,
                                        jArray.getJSONObject(i).getString("payload"),
                                        jArray.getJSONObject(i).getString("issue_qty")
                                ));

                                payload_label.add( new Payload_list(
                                        jArray.getJSONObject(i).getString("id"),
                                        scrap_flg,
                                        jArray.getJSONObject(i).getString("payload"),
                                        jArray.getJSONObject(i).getString("issue_qty")
                                ));

                                if (i == 0){
                                    payload_repack.add( new Payload_list(
                                            jArray.getJSONObject(i).getString("id"),
                                            scrap_flg,
                                            jArray.getJSONObject(i).getString("payload"),
                                            jArray.getJSONObject(i).getString("issue_qty")
                                    ));
                                }
                            }
                            AlertConfirmPrint_Repack();

                            Log.d(getString(R.string.tag), "payload: " + payload_label.size()+"|"+payload_repack.size());
                        } else {
                            showWarning("Can't prepare the label!!");
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            }.execute();

        } catch (Exception e) {
            Log.e(getString(R.string.tag), e.getMessage());
        }
    }

    private void AlertConfirmPrint_Repack() {
        try {
            SweetAlertDialog sweetAlertDialog = new SweetAlertDialog(OutboutManualRecheck_Activity.this, SweetAlertDialog.SUCCESS_TYPE);
            sweetAlertDialog.setTitleText("SUCCESS");
            sweetAlertDialog.setContentText("Do you want to print the new " + map_payload.get("1").getQty() + " " + label.getString("lbl_unit") + " label?");
            sweetAlertDialog.setCancelText("No");
            sweetAlertDialog.showCancelButton(true);
            sweetAlertDialog.setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                @Override
                public void onClick(SweetAlertDialog sDialog) {
                    sDialog.dismiss();
                    payload_print = payload_repack.stream()
                            .collect(Collectors.toList());

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

                    } else {
                        Log.d(getString(R.string.tag), "payload_print No: " + payload_print.size());
                        Command_Print();
                    }

                }
            });
            sweetAlertDialog.setConfirmText("Yes");
            sweetAlertDialog.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                @Override
                public void onClick(SweetAlertDialog sDialog) {
                    sDialog.dismiss();
                    payload_print = payload_label.stream()
                            .collect(Collectors.toList());
                    if (Settings.getMgmtList().get("skip_print").trim().equals("1")) {
                        AlertConfirmPrint();

                    } else {

                        Log.d(getString(R.string.tag), "payload_print yes: " + payload_print.size());
                        Command_Print();
                    }
                }
            });
            sweetAlertDialog.show();

        }catch (JSONException e){
            e.printStackTrace();
        }
    }

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

        PRINT_TIMES = 0;
        LABEL_QTY = payload_print.size();
        stopThread = false;
        Log.d("Thread.sleep", "stopThread: " + stopThread + ":" + PRINT_TIMES+"-->"+LABEL_QTY);

        ExampleRunnable runnable = new ExampleRunnable();
        new Thread(runnable).start();

    }

    class ExampleRunnable implements Runnable {

        @Override
        public void run() {
            while (!stopThread) {
                try {
                    Print_Label();
                    Thread.sleep(3000);
                    Log.d("Thread.sleep2", "stopThread: " + stopThread);

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void Print_Label() {
        Log.d(getString(R.string.tag), "PRINT_TIMES1: " + PRINT_TIMES+"="+LABEL_QTY);

        PRINT_TIMES = (PRINT_TIMES + 1);
        Log.d(getString(R.string.tag), "PRINT_TIMES2: " + PRINT_TIMES+"="+LABEL_QTY);

        if (PRINT_TIMES == LABEL_QTY){
            stopThread = true;
            Log.d("Thread.sleep if", "stopThread: " + stopThread);
        }

        Payload_list payload_l = payload_print.get(PRINT_TIMES-1);
        String payload = payload_l.getPayload();
        String scrap_flg = payload_l.getScrap_flg();
        Log.d("payload", payload_l.getId()+"|" + payload);

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

            String tmp = String.format(
                    "%s %s%s%s\r\n%s"
                    , "PST"
                    , Settings.getMgmtList().get("printer_preset")
                    , Settings.getPrinter()
                    , scrap_flg
//                    , Settings.getDeviceNo()
                    , payload

            );

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

                    if (response.equals("OK")) {
                        if (stopThread == true) {
                            alert.dismiss();
                            AlertConfirmPrint();
                        }
                    } else {
                        Unblock_button();
                        alert.dismiss();
                        new SweetAlertDialog(OutboutManualRecheck_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText("Can't connect to print server")
                                .show();

                    }
                }
            }.execute();
            throw new JSONException(err_msg);
        } catch (JSONException e) {
            Log.e(getString(R.string.tag), "ERROR: " + e.getMessage());
        }
    }


    private void AlertConfirmPrint() {
        try {
            new SweetAlertDialog(OutboutManualRecheck_Activity.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();
                            Unblock_button();
                        }
                    })
                    .setConfirmText("Yes")
                    .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sDialog) {
                            sDialog.dismiss();
                            Confirm_Label();
                        }
                    })
                    .show();
        }catch (WindowManager.BadTokenException e) {
            new SweetAlertDialog(OutboutManualRecheck_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("WARNING")
                    .setContentText("Please check the label status on Pegasus!")
                    .show();

        }catch (Exception e){
            new SweetAlertDialog(OutboutManualRecheck_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("WARNING")
                    .setContentText("Please check the label status on Pegasus!")
                    .show();
        }

    }

    private void Confirm_Label() {
        Log.d(getString(R.string.tag), "payload_print: " + payload_print.size());
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "RELABELING/CONFIRM/CONFIRM");
            JSONArray jArray = new JSONArray();
            for (int i = 0; i < payload_print.size(); i++){
                Payload_list list = payload_print.get(i);
                Map<String, String> jsParams = new HashMap<>();
                jsParams.put("label_id", list.getId());
                JSONObject jsonObject = new JSONObject(jsParams);
                jArray.put(jsonObject);
            }
            json.put("value",jArray);

            new AsyncHttpClient(getApplicationContext(),
                    Settings.getMgmtList().get("web_api") + "/ht_api.php",
                    json.toString()) {
                @Override
                protected void onFinished(String response, int resp_code) {
                    Log.d(getString(R.string.tag), "response: " + response);

                    try{
                        JSONObject jsonObject = new JSONObject(response);
                        String status = jsonObject.getString("status");
                        int affected_rows = jsonObject.getInt("affected_rows");

                        if (status.trim().equals("success") && affected_rows > 0){
                            SendOutbound();

                        }else {
                            Unblock_button();
                            String error = jsonObject.getString("error");
                            new SweetAlertDialog(OutboutManualRecheck_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                    .setTitleText("ERROR")
                                    .setContentText(error)
                                    .show();
                        }
                    }catch (JSONException e) {
                        Unblock_button();
                        new SweetAlertDialog(OutboutManualRecheck_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();

        }catch (JSONException e) {
            Unblock_button();
            new SweetAlertDialog(OutboutManualRecheck_Activity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage())
                    .show();
        }
    }

    private void SendOutbound() {
        Log.d(getString(R.string.tag), "SendOutbound: " + map_payload.size());
        Log.d(getString(R.string.tag), "Outbound sending_ticket: " + sending_ticket.get(0));
        if (sending_ticket.get(0) == 0) {
//            return;
            finish();
        }
        sending_ticket.set(0,0);
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "OUTBOUND/MANUAL/DETAIL/CONFIRM");
            JSONArray jsonArray = new JSONArray();
            for (JSONObject item : label_scan.values()) {
                Map<String, String> jsonParams = new HashMap<>();
                jsonParams.put("item_id", item.getString("lbl_part_no"));
                jsonParams.put("item_name", item.getString("lbl_part_name"));
                jsonParams.put("lot_no", item.getString("lot_no"));
                jsonParams.put("ref_sch_id", "0");
                jsonParams.put("package_id", item.getString("control_unit"));
                jsonParams.put("unit_qty", item.getString("control_unit"));
                jsonParams.put("package_qty", item.getString("act_stock_qty"));
                jsonParams.put("qty", item.getString("act_stock_qty"));
                jsonParams.put("location_id", item.getString("last_location_id"));
                jsonParams.put("location_name", item.getString("last_location_name").trim().equals("null") ? "": item.getString("last_location_name").trim());
                jsonParams.put("label_id", item.getString("label_id"));
                jsonParams.put("inspection_flg", "0");
                jsonParams.put("status", "2"); // OUT_STORE = 3;
                jsonParams.put("slip_divide", "4");
                jsonParams.put("create_user_id", Settings.getLoginUser().getId());
                jsonParams.put("ng", item.getString("lbl_ng"));
                jsonParams.put("supplier_id", item.getString("lbl_supplier_id"));
                jsonParams.put("supplier_name", item.getString("lbl_supplier").trim().equals("null") ? "": item.getString("lbl_supplier").trim());
                JSONObject jsonObject = new JSONObject(jsonParams);
                jsonArray.put(jsonObject);
            }

            json.put("value",jsonArray);
            if (jsonArray.length() == 0)
                return;

            new AsyncHttpClient(getApplicationContext(),
                    Settings.getMgmtList().get("web_api") + "/ht_api.php",
                    json.toString()) {
                @Override
                protected void onFinished(String response, int resp_code) {
                    Log.d(getString(R.string.tag), "response: " + response);
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        String status = jsonObject.getString("status");
                        int affected_rows = jsonObject.getInt("affected_rows");

                        if (status.equals("success") && affected_rows > 0) {
                            Log.d(getString(R.string.tag), "success: " + response);
                            Log.d(getString(R.string.tag), "Outbound sending_ticket: " + sending_ticket.get(0));

                            if (repack_label != null ){
                                SendInbound();
                            }else {
                                finish();
//                                showSuccess("Outbound Completed");
//                                Clear_layout();
                            }
                        }else{
                            Unblock_button();
                            showWarning("Can't Outbound");
                        }

                    } catch (JSONException e) {
                        Unblock_button();
                        e.printStackTrace();
                    }

                }
            }.execute();

        } catch (Exception e) {
            Unblock_button();
            Log.e(getString(R.string.tag), e.getMessage());
        }
    }

    private void SendInbound() {
        Log.d(getString(R.string.tag), "SendInbound map_payload: " + map_payload.size());
        Log.d(getString(R.string.tag), "Inbound sending_ticket: " + sending_ticket.get(1));

        if (sending_ticket.get(1) == 0) {
//            return;
            finish();
        }
        sending_ticket.set(1,0);
        try {
            JSONObject json = new JSONObject();
            Map<String, String> jsonParams = new HashMap<>();
            json.put("cmd", "INBOUND/MANUAL/DETAIL/CONFIRM");
            JSONArray jsonArray = new JSONArray();

            for (String key : map_payload.keySet()){
                Payload_list payload_label = map_payload.get(key);

                    jsonParams.put("ref_sch_id", "0");
                    jsonParams.put("label_id", payload_label.getId());
                    jsonParams.put("package_qty", payload_label.getQty());
                    jsonParams.put("qty",payload_label.getQty());
                    jsonParams.put("item_id", repack_label.getString("lbl_part_no"));
                    jsonParams.put("lot_no", repack_label.getString("lot_no"));
                    jsonParams.put("item_name", repack_label.getString("lbl_part_name"));
                    jsonParams.put("package_id", repack_label.getString("lbl_unit"));
                    jsonParams.put("unit_qty", repack_label.getString("lbl_unit"));
                    jsonParams.put("location_id", repack_label.getString("last_location_id"));
                    jsonParams.put("location_name", repack_label.getString("last_location_name").trim().equals("null") ? "" : repack_label.getString("last_location_name"));
                    jsonParams.put("inspection_flg","0");
                    jsonParams.put("status", "1");
                    jsonParams.put("slip_divide", "3");
                    jsonParams.put("create_user_id", Settings.getLoginUser().getId());
                    jsonParams.put("ng", repack_label.getString("lbl_ng"));
                    jsonParams.put("supplier_id", repack_label.getString("lbl_supplier_id").trim().equals("null") ? "" : repack_label.getString("lbl_supplier_id"));
                    jsonParams.put("supplier_name", repack_label.getString("lbl_supplier").trim().equals("null") ? "" : repack_label.getString("lbl_supplier"));

                JSONObject jsonObject = new JSONObject(jsonParams);
                jsonArray.put(jsonObject);
            }
            json.put("value",jsonArray);

            new AsyncHttpClient(getApplicationContext(),
                    Settings.getMgmtList().get("web_api") + "/ht_api.php",
                    json.toString()) {
                @Override
                protected void onFinished(String response, int resp_code) {
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        Log.d(getString(R.string.tag),"response"+ response);
                        String status = jsonObject.getString("status");
                        int affected_rows = jsonObject.getInt("affected_rows");

                        if (status.trim().equals("success") && affected_rows > 0){

                            Log.d(getString(R.string.tag), "Inbound sending_ticket: " + sending_ticket.get(1));
                            SendOutbound_repack();

                        }else {
                            Unblock_button();
                            String error = jsonObject.getString("error");
                            new SweetAlertDialog(OutboutManualRecheck_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                    .setTitleText("ERROR")
                                    .setContentText(error)
                                    .show();

                        }
                    }catch (JSONException e) {
                        Unblock_button();
                        new SweetAlertDialog(OutboutManualRecheck_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();
        }catch (Exception e) {
            Unblock_button();
            new SweetAlertDialog(OutboutManualRecheck_Activity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage())
                    .show();
        }
    }

    private void SendOutbound_repack() {
        Log.d(getString(R.string.tag), "SendInbound SendOutbound_repack: " +map_payload.size());
        Log.d(getString(R.string.tag), "label_id: " +map_payload.get("1").getId());
        Log.d(getString(R.string.tag), "Outbound_Re sending_ticket: " + sending_ticket.get(2));
        if (sending_ticket.get(2) == 0) {
//            return;
            finish();
        }
        sending_ticket.set(2,0);
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "OUTBOUND/MANUAL/DETAIL/CONFIRM");
            JSONArray jsonArray = new JSONArray();

                Map<String, String> jsonParams = new HashMap<>();
                jsonParams.put("item_id", repack_label.getString("lbl_part_no"));
                jsonParams.put("item_name", repack_label.getString("lbl_part_name"));
                jsonParams.put("lot_no", repack_label.getString("lot_no"));
                jsonParams.put("ref_sch_id", "0");
                jsonParams.put("package_id", repack_label.getString("lbl_unit"));
                jsonParams.put("unit_qty", repack_label.getString("lbl_unit"));
                jsonParams.put("package_qty", repack_label.getString("pick_qty"));
                jsonParams.put("qty", repack_label.getString("pick_qty"));

                jsonParams.put("location_id", repack_label.getString("last_location_id"));
                jsonParams.put("location_name", repack_label.getString("last_location_name").trim().equals("null") ? "" : repack_label.getString("last_location_name"));
                jsonParams.put("label_id", map_payload.get("1").getId());
                jsonParams.put("inspection_flg", "0");
                jsonParams.put("status", "2");
                jsonParams.put("slip_divide", "4");
                jsonParams.put("create_user_id", Settings.getLoginUser().getId());
                jsonParams.put("ng", repack_label.getString("lbl_ng"));
                jsonParams.put("supplier_name", repack_label.getString("lbl_supplier_id").trim().equals("null") ? "" : repack_label.getString("lbl_supplier_id"));
                jsonParams.put("supplier_id", repack_label.getString("lbl_supplier").trim().equals("null") ? "" : repack_label.getString("lbl_supplier"));

                JSONObject jsonObject = new JSONObject(jsonParams);
                jsonArray.put(jsonObject);


            json.put("value",jsonArray);
            if (jsonArray.length() == 0)
                return;

            new AsyncHttpClient(getApplicationContext(),
                    Settings.getMgmtList().get("web_api") + "/ht_api.php",
                    json.toString()) {
                @Override
                protected void onFinished(String response, int resp_code) {
                    Log.d(getString(R.string.tag), "response: " + response);
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        String status = jsonObject.getString("status");
                        int affected_rows = jsonObject.getInt("affected_rows");

                        if (status.equals("success") && affected_rows > 0) {
                            Log.d(getString(R.string.tag), "success: " + response);

                            Log.d(getString(R.string.tag), "Outbound_RE sending_ticket: " + sending_ticket.get(2));

                            finish();
//                            showSuccess("Outbound Completed");
//                            Clear_layout();
                        }else{
                            Unblock_button();
                            showWarning("Can't Outbound");
                        }

                    } catch (JSONException e) {
                        Unblock_button();
                        e.printStackTrace();
                    }

                }
            }.execute();

        } catch (Exception e) {
            Unblock_button();
            Log.e(getString(R.string.tag), e.getMessage());
        }
    }

    private void Block_button() {
        b_confirm = true;
        btn_confirm.setEnabled(false);
        btn_confirm.setBackgroundResource(R.drawable.button_background_gray);
    }

    private void Unblock_button() {
        b_confirm = false;
        btn_confirm.setEnabled(true);
        btn_confirm.setBackgroundResource(R.drawable.button_background_blue);
    }


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

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyMapping.Down.getId() || keyCode == KeyMapping.P2.getId()
                || keyCode == KeyMapping.ENT.getId())
        {
            switch (KeyMapping.fromId(keyCode)) {
                case Down:
                    finish();
                    break;

                case P2:
                    Clear_layout();
                    break;

                case ENT://confirm
                    if (b_confirm == false) {
                        Block_button();   if (b_confirm == false) {
                            Block_button();
                            Check_Total();
                        }
                    }
                    break;
            }
        }

        return super.onKeyUp(keyCode, event);
    }

}