package com.tomas.lps_asi;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.keyence.autoid.sdk.scan.DecodeResult;
import com.tomas.lps_asi.Adapter.Material_Adapter;
import com.tomas.lps_asi.Adapter.RankCard_Adapter;
import com.tomas.lps_asi.ListData.Item_Lists;
import com.tomas.lps_asi.ListData.Machine_Lists;
import com.tomas.lps_asi.ListData.Material_Lists;
import com.tomas.lps_asi.ListData.RankCard_Lists;
import com.tomas.lps_asi.ListData.User_Lists;
import com.tomas.lps_asi.lib.KeyMapping;
import com.tomas.lps_asi.lib.MyAlert;
import com.tomas.lps_asi.lib.Settings;
import com.tomas.lps_asi.lib.common.AsyncHttpClient;
import com.tomas.lps_asi.lib.common.AsyncTcpClient;
import com.tomas.lps_asi.lib.common.Scanner;
import com.tomas.lps_asi.lib.common.Utils;

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

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import cn.pedant.SweetAlert.SweetAlertDialog;

public class BalanceLabel_Activity extends Scanner implements View.OnClickListener {
    TextView txt_date, txt_user, txt_machine, txt_name, txt_rank, txt_lot_no, txt_balance, txt_reel_qty, txt_message;
    EditText edt_material;
    RecyclerView view_material;
    String str_date, machine_no, mc_product_type, printer_ip, item_product_type, ICS_CODE, RANK_CARD, RANK, NAME, CUSTOMER, QTY_REEL,
            RANK_CARD_LOT, dt_to_server, Material_a, Material_b;
    Calendar calendar;
    EditText edt_label_qty;
    boolean scan_rank_card, scan_machine, b_print, scan_lot_no, error_print;
    int scan_times, REQUEST_REEL_QTY, QTY_RANK_CARD, LABEL_QTY, PRINT_TIMES, DIGIT;
    SimpleDateFormat date_time_fm, date_fm, date_taping_fm;
    ConstraintLayout layout_alert;
    Map<String, Material_Lists> map_material;
    Map<String, Machine_Lists>map_machine;
    List<Material_Lists>list_material;
    Material_Adapter material_adapter;
    Button btn_print;
    ImageButton btn_add;
    Map<String, Item_Lists> map_item;
    private volatile boolean stopThread = true;

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

        default_view = (EditText) findViewById(R.id.txt_label_issue_tmp);
        calendar = Calendar.getInstance();
        date_time_fm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        date_fm = new SimpleDateFormat("yyyy-MM-dd");
        date_taping_fm = new SimpleDateFormat("yyyyMMdd");
//        str_date = date_fm.format(calendar.getTime());

        scan_times = 0;
        b_print = false;
        scan_machine = false;
        scan_rank_card  = false;
        scan_lot_no = false;
        stopThread = true;
        error_print = false;

        map_material = new LinkedHashMap<>();
        map_machine = new LinkedHashMap<>();
        map_item = new LinkedHashMap<>();

        list_material = new ArrayList<Material_Lists>();

        layout_alert = (ConstraintLayout)findViewById(R.id.layout_alert);

        btn_print = (Button)findViewById(R.id.btn_print);
        btn_add = (ImageButton)findViewById(R.id.btn_add);

        txt_date = (TextView) findViewById(R.id.txt_date);
//        txt_date.setText(str_date);
        txt_user = (TextView) findViewById(R.id.txt_user);
        txt_machine = (TextView) findViewById(R.id.txt_machine);
        txt_name = (TextView) findViewById(R.id.txt_name);
        txt_rank = (TextView) findViewById(R.id.txt_rank);
        txt_lot_no = (TextView) findViewById(R.id.txt_lot_no);
        txt_balance = (TextView) findViewById(R.id.txt_balance);
        txt_reel_qty = (TextView) findViewById(R.id.txt_reel_qty);
        txt_message = (TextView)findViewById(R.id.txt_message);

        edt_material = (EditText)findViewById(R.id.edt_material);

        edt_label_qty = (EditText) findViewById(R.id.edt_label_qty);
        edt_label_qty.requestFocus();
        edt_label_qty.setShowSoftInputOnFocus(false);

        view_material = (RecyclerView) findViewById(R.id.view_material);
        view_material.setHasFixedSize(true);
        view_material.setRecycledViewPool(new RecyclerView.RecycledViewPool());
        view_material.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        view_material.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        view_material.setItemAnimator(new DefaultItemAnimator());
    }

    @Override
    protected void onStart() {
        super.onStart();

        Check_Time();

    }

    private void Check_Time() {
        calendar = Calendar.getInstance();
        try {
            Date today = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("hh:mm aa");
            String current_time = sdf.format(today);
            Date start = sdf.parse("08:00 AM");
            Date current = sdf.parse(current_time);

            if (current.before(start)) {
                calendar.add(Calendar.DATE, -1);
            }
            str_date = date_fm.format(calendar.getTime());
            txt_date.setText(str_date);

        } catch (ParseException e) {
            // Invalid date was entered
        }
    }

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

            case R.id.btn_clear:
                if (error_print == false) {
                    Clear_Layout();
                }
                break;

            case R.id.btn_add:
                String input = edt_material.getText().toString().trim();
                if (!input.trim().equals("")) {
                    adjust_map_material(input);
                }
                break;
            case R.id.btn_print:
                //print
                if (b_print == false){
                    if (error_print == true){//print error --> print again
                        Command_Print();

                    }else {
                        Block_button();
                        Check_DataInput();
                    }
                }

                break;
        }
    }

    private void Check_DataInput() {
        if (txt_user.getText().toString().trim().equals("")){
            Unblock_button();
            new SweetAlertDialog(BalanceLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("แจ้งเตือน")
                    .setContentText("กรุณาสแกนรหัสพนักงาน!")
                    .show();
        }else {
            if (map_material.size() == 2){
                Insert_RankCard();
            }else {
                Unblock_button();
                new SweetAlertDialog(BalanceLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                        .setTitleText("แจ้งเตือน")
                        .setContentText("กรุณากรอกข้อมูลให้ครบ!")
                        .show();
            }
        }
    }


    private void Block_button() {
        b_print = true;
        btn_print.setEnabled(false);
        btn_print.setBackgroundResource(R.drawable.button_backgroup_gray);
    }

    private void Unblock_button() {
        b_print = false;
        btn_print.setEnabled(true);
        btn_print.setBackgroundResource(R.drawable.button_backgroup_green);
    }

    private void Clear_Layout() {
        scan_times = 0;
        stopThread = true;
        b_print = false;
        scan_machine = false;
        scan_rank_card  = false;
        scan_lot_no = false;
        error_print = false;
        txt_machine.setText("");
        txt_name.setText("");
        txt_rank.setText("");
        txt_rank.setText("");
        txt_lot_no.setText("");
        edt_material.setText("");
        txt_balance.setText("0");
        txt_reel_qty.setText("0");
        edt_label_qty.setText("1");

        map_material.clear();
        Set_view_material();
        Unblock_button();

    }

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

        if (error_print == true)
            return;

        try {
            Log.d(getString(R.string.tag), "scan data : " + data);

            if (scan_lot_no == true) {// scan material
                String material = data.trim();
                edt_material.setText(material);
                adjust_map_material(material);

            }else if (scan_rank_card == true) {// scan rank card lot no.
                    RANK_CARD_LOT = data;
                    scan_lot_no = true;
                    Check_RankCard(RANK_CARD, RANK_CARD_LOT, QTY_RANK_CARD);

            }else{
                Log.d(getString(R.string.tag), "scan else  : " + data);

                if (data.length() == 6) {//scan user
//                    Check_User(data);
                    if (Settings.getMap_user().containsKey(data)){
                        txt_user.setText(data);
                        User_Lists lists = Settings.getMap_user().get(data);
                        String nameEng = lists.getNameEng();
                        Log.d(getString(R.string.tag), "nameEng : " + nameEng);
                    }else {
                        txt_user.setText("");
                        new SweetAlertDialog(BalanceLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                .setTitleText("แจ้งเตือน")
                                .setContentText("ไม่พบรหัสพนักงาน!")
                                .show();
                    }
                } else if (data.substring(0,2).trim().equals("TP") ) {//scan machine
                    if (txt_user.getText().toString().trim().equals("")) {
                        new SweetAlertDialog(BalanceLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                .setTitleText("แจ้งเตือน")
                                .setContentText("กรุณาสแกนรหัสพนักงาน!")
                                .show();
                    } else {
                        Check_Machine(data);
                    }
                }else {//scan rank card or another.
                    if (txt_machine.getText().toString().trim().equals("")){//check scan machine
                        new SweetAlertDialog(BalanceLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                .setTitleText("แจ้งเตือน")
                                .setContentText("กรุณาสแกนเครื่องจักร!")
                                .show();
                    }else {
                        txt_lot_no.setText("");
                        txt_name.setText("");
                        txt_rank.setText("");
                        edt_material.setText("");
                        txt_balance.setText("0");
                        txt_reel_qty.setText("0");

                        RANK_CARD = data.trim();
                        ICS_CODE = data.trim().substring(0, 10);
                        Check_ICS_Code(ICS_CODE);
                    }
                }
            }

//                } else if (data.length() == 20 || data.length() == 23) {//scan rank card
//
//                    if (txt_machine.getText().toString().trim().equals("")){//check scan machine
//                        new SweetAlertDialog(BalanceLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
//                                .setTitleText("แจ้งเตือน")
//                                .setContentText("กรุณาสแกนเครื่องจักร!")
//                                .show();
//                    }else{
//                        txt_lot_no.setText("");
//                        txt_name.setText("");
//                        txt_rank.setText("");
//                        edt_material.setText("");
//                        txt_balance.setText("0");
//                        txt_reel_qty.setText("0");
//
//                        RANK_CARD = data.trim();
//                        ICS_CODE = RANK_CARD.substring(0, 10);
//
//                        String qty = "";
//                        if (RANK_CARD.length() == 20) {
//                            RANK = RANK_CARD.substring(10, 15);
//                            qty = RANK_CARD.substring(15, 20);
//
//                        } else {
//                            RANK = RANK_CARD.substring(10, 18);
//                            qty = RANK_CARD.substring(18, 23);
//                        }
//
//                        QTY_RANK_CARD = Integer.parseInt(qty);
//                        Check_Item(ICS_CODE, RANK);//for check type
//                    }
//                }
//            }
            Utils.hideKeyboardFrom(getApplicationContext(), default_view);

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

    private void Check_ICS_Code(String ics_code) {
        map_item.clear();
        try {
            txt_message.setText("Please wait, searching data...");
            layout_alert.setVisibility(View.VISIBLE);

            JSONObject json = new JSONObject();
            json.put("cmd", "search");
            json.put("ics_code", ics_code);

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

                    try {
                        JSONArray jArray = new JSONArray(response);
                        if (jArray.length() == 0){
                            layout_alert.setVisibility(View.GONE);
                            new SweetAlertDialog(BalanceLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("แจ้งเตือน")
                                    .setContentText("ไม่พบ ICS Code!")
                                    .show();
                        }else {
                            for (int i = 0; i < jArray.length(); i++) {
                                DIGIT =   jArray.getJSONObject(i).getInt("Digit");
                                map_item.put(jArray.getJSONObject(i).getString("ICS_Code").trim()+jArray.getJSONObject(i).getString("Rank").trim(),
                                        new Item_Lists(
                                                jArray.getJSONObject(i).getString("ICS_Code").trim(),
                                                jArray.getJSONObject(i).getString("Product_Name").trim(),
                                                jArray.getJSONObject(i).getString("Rank").trim(),
                                                jArray.getJSONObject(i).getString("Digit").trim(),
                                                jArray.getJSONObject(i).getString("Customer_Reference").trim(),
                                                jArray.getJSONObject(i).getString("Qty_Reel").trim(),
                                                jArray.getJSONObject(i).getString("Type").trim()));

                            }
                            layout_alert.setVisibility(View.GONE);
                            try {
                                //subString RankCard
                                Log.d(getString(R.string.tag), "RANK_CARD: " + RANK_CARD);
                                RANK = RANK_CARD.substring(10, 10 + DIGIT);
                                Log.d(getString(R.string.tag), "RANK: " + RANK);
                                String qty = RANK_CARD.substring(10 + DIGIT);
                                QTY_RANK_CARD = Integer.parseInt(qty);
                                Log.d(getString(R.string.tag), "qty: " + qty + " / " + String.valueOf(QTY_RANK_CARD));

                                String key = ics_code + RANK;
                                Log.d(getString(R.string.tag), "key: " + key);

                                    if (map_item.containsKey(key)) {//get data ics_code+rank
                                        Item_Lists item = map_item.get(key);
                                        NAME = item.getProduct_Name();
                                        CUSTOMER = item.getCustomer_Reference();
                                        QTY_REEL = item.getQty_Reel();
                                        item_product_type = item.getType();
                                        Log.d(getString(R.string.tag), "Item: " + NAME + "|" + CUSTOMER + "|" + QTY_REEL + "|" + item_product_type);

                                        //check type
                                        if (map_machine.containsKey(item_product_type)) {
                                            Machine_Lists mc = map_machine.get(item_product_type);
                                            machine_no = mc.getMachine_No();
                                            mc_product_type = mc.getType();
                                            printer_ip = mc.getPrinter_IP();

                                            scan_rank_card = true;
                                            txt_name.setText(NAME);
                                            txt_rank.setText(RANK);
                                            txt_reel_qty.setText(QTY_REEL);
                                            REQUEST_REEL_QTY = Integer.parseInt(QTY_REEL);
                                            layout_alert.setVisibility(View.GONE);

                                        } else {
                                            MyAlert alert = new MyAlert(BalanceLabel_Activity.this);
                                            alert.setMessage("Type ไม่ตรงกัน!");
                                            alert.show();

                                        }
                                    } else {
                                        new SweetAlertDialog(BalanceLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                                .setTitleText("แจ้งเตือน")
                                                .setContentText("ไม่พบ Rank : " + RANK)
                                                .show();
                                    }
                            }catch (Exception e){
                                layout_alert.setVisibility(View.GONE);
                                new SweetAlertDialog(BalanceLabel_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                        .setTitleText("ERROR")
                                        .setContentText("sub string rank card error!")
                                        .show();
                            }
                        }
                    }catch (JSONException e) {
                        layout_alert.setVisibility(View.GONE);
                        new SweetAlertDialog(BalanceLabel_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();

        }catch (JSONException e) {
            layout_alert.setVisibility(View.GONE);
            new SweetAlertDialog(BalanceLabel_Activity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage())
                    .show();
        }
    }

    private void adjust_map_material(String material) {
        if (map_material.containsKey(material)) {
            map_material.remove(material);
            Set_view_material();
        } else {
            if (map_material.size() < 2) {
                map_material.put(material, new Material_Lists(
                        material));

                Log.d(getString(R.string.tag), "map_material: " + map_material.size());
                Set_view_material();


            } else {
                edt_material.setText("");
                new SweetAlertDialog(BalanceLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                        .setTitleText("แจ้งเตือน")
                        .setContentText("Material ครบแล้ว! \n หากต้องการแก้ไขข้อมูล กดปุ่ม clear หรือ ทำรายการซ้ำ")
                        .show();
            }
        }
    }

    private void Set_view_material() {
        list_material.clear();
        for (String key : map_material.keySet()){
            Material_Lists list = map_material.get(key);
            list_material.add(new Material_Lists(
                    list.getMaterial()));
        }
        material_adapter = new Material_Adapter(list_material, BalanceLabel_Activity.this);
        view_material.setAdapter(material_adapter);
        edt_material.setText("");

    }

    private void Insert_RankCard() {
        calendar = Calendar.getInstance();
        calendar = (Calendar) calendar.clone();
        dt_to_server = date_time_fm.format(calendar.getTime());
        Log.d(getString(R.string.tag), "dt_to_server : " + dt_to_server);

        try {
            layout_alert.setVisibility(View.VISIBLE);
            txt_message.setText("Please wait, saving data...");

            JSONObject json = new JSONObject();
            json.put("cmd", "add");
            JSONArray jsonArray = new JSONArray();

                Map<String, String> jsonParams = new HashMap<>();
                jsonParams.put("rank_card", RANK_CARD);
                jsonParams.put("lot_no", RANK_CARD_LOT);
                jsonParams.put("ics_code", ICS_CODE);
                jsonParams.put("product_name", txt_name.getText().toString().trim());
                jsonParams.put("rank", RANK);
                jsonParams.put("qty", txt_balance.getText().toString().trim());
                jsonParams.put("qty_used", txt_balance.getText().toString().trim());
                jsonParams.put("balance", "0");
                jsonParams.put("taping_lot_no", RANK_CARD_LOT);
                jsonParams.put("create_dt", dt_to_server);
                JSONObject jsonObj = new JSONObject(jsonParams);
                jsonArray.put(jsonObj);

            json.put("rank_card_datas",jsonArray);

            new AsyncHttpClient(getApplicationContext(),
                    Settings.getMgmtList().get("web_api") + "/rank_card.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) {
                            Insert_TapingLabel();

                        } else {
                            Unblock_button();
                            layout_alert.setVisibility(View.GONE);
                            new SweetAlertDialog(BalanceLabel_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                    .setTitleText("ERROR")
                                    .setContentText("Can't insert RankCard")
                                    .show();
                        }
                    } catch (JSONException e) {
                        Unblock_button();
                        layout_alert.setVisibility(View.GONE);
                        new SweetAlertDialog(BalanceLabel_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();
        } catch (Exception e) {
            Unblock_button();
            layout_alert.setVisibility(View.GONE);
            new SweetAlertDialog(BalanceLabel_Activity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage())
                    .show();
        }
    }

    private void Insert_TapingLabel() {
        calendar = Calendar.getInstance();
        calendar = (Calendar) calendar.clone();
        dt_to_server = date_time_fm.format(calendar.getTime());
        Log.d(getString(R.string.tag), "dt_to_server : " + dt_to_server);

        int i = 0;
        for (String key : map_material.keySet()) {
            Material_Lists lists = map_material.get(key);
            i = i+1;
            if (i == 1){
                Material_a = lists.getMaterial();
            }else {
                Material_b = lists.getMaterial();
            }
        }
        try {
            layout_alert.setVisibility(View.VISIBLE);
            txt_message.setText("Please wait, saving data...");

            JSONObject json = new JSONObject();
            json.put("cmd", "add");
            JSONArray jsonArray = new JSONArray();

            Map<String, String> jsonParams = new HashMap<>();
            jsonParams.put("taping_lot_no", RANK_CARD_LOT);
            jsonParams.put("ics_code", ICS_CODE);
            jsonParams.put("product_name",  txt_name.getText().toString().trim());
            jsonParams.put("rank",  RANK);
            jsonParams.put("type",  mc_product_type);
            jsonParams.put("cust_ref", CUSTOMER);
            jsonParams.put("machine_no", machine_no);
            jsonParams.put("taping_qty", txt_balance.getText().toString().trim());
            jsonParams.put("label_qty", edt_label_qty.getText().toString().trim());
            jsonParams.put("label_type", Settings.getLabelType());
            jsonParams.put("remark", "");
            jsonParams.put("material_a", Material_a);
            jsonParams.put("material_b", Material_b);
            jsonParams.put("create_dt", dt_to_server);
            jsonParams.put("create_user_id", txt_user.getText().toString().trim());
            JSONObject jsonObj = new JSONObject(jsonParams);
            jsonArray.put(jsonObj);

            json.put("label_datas",jsonArray);

            new AsyncHttpClient(getApplicationContext(),
                    Settings.getMgmtList().get("web_api") + "/taping_label.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) {

                            Command_Print();

                        } else {
                            Unblock_button();
                            layout_alert.setVisibility(View.GONE);
                            new SweetAlertDialog(BalanceLabel_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                    .setTitleText("ERROR")
                                    .setContentText("Can't Insert_TapingLabel")
                                    .show();
                        }
                    } catch (JSONException e) {
                        Unblock_button();
                        layout_alert.setVisibility(View.GONE);
                        new SweetAlertDialog(BalanceLabel_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();
        } catch (Exception e) {
            Unblock_button();
            layout_alert.setVisibility(View.GONE);
            new SweetAlertDialog(BalanceLabel_Activity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage())
                    .show();
        }
    }

    private void Command_Print() {
        layout_alert.setVisibility(View.VISIBLE);
        txt_message.setText("Send printing data....");

        String str_qty_label = edt_label_qty.getText().toString().trim();
        LABEL_QTY = Integer.parseInt(str_qty_label);
        PRINT_TIMES = 0;
        stopThread = false;
        Log.d("Thread.sleep", "stopThread: " + stopThread+":"+PRINT_TIMES);

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

    }

    class ExampleRunnable implements Runnable {

        @Override
        public void run() {
            while (!stopThread) {
                try {
                    Print_Label();
                    Thread.sleep(4000);
                    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);
        }

        String err_msg = "";
        try {
            err_msg = "Server connection failed!\nPlease contact leader.";
            String payload = String.format(
                    "%s|%s|%s|%s|%s"
                    , ICS_CODE
                    , NAME
                    , txt_balance.getText().toString().trim()
                    , RANK_CARD_LOT
                    , CUSTOMER);

            String tmp = String.format(
                    "%s %s\r\n%s%s"
                    , "PST"
                    ,printer_ip
                    , ""
                    , payload
            );

            Log.d(getString(R.string.tag), "payload: " + payload);
            new AsyncTcpClient(getApplicationContext(),
                    Settings.getMgmtList().get("printer_server_ip"),
                    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) {
                            Clear_Layout();
                            layout_alert.setVisibility(RelativeLayout.GONE);
                            Toast.makeText(BalanceLabel_Activity.this, "Print : OK", Toast.LENGTH_SHORT).show();
                            new SweetAlertDialog(BalanceLabel_Activity.this, SweetAlertDialog.SUCCESS_TYPE)
                                    .setTitleText("SUCCESS")
                                    .setContentText("Print : OK")
                                    .show();
                        }

                    } else {
                        error_print = true;
                        layout_alert.setVisibility(RelativeLayout.GONE);
                        Unblock_button();
                        new SweetAlertDialog(BalanceLabel_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());

        }
//        layout_alert.setVisibility(RelativeLayout.GONE);
//        Unblock_button();
    }

    private void Check_Item(String ics_code, String rank) {
        try {
            txt_message.setText("Please wait, searching data...");
            layout_alert.setVisibility(View.VISIBLE);

            JSONObject json = new JSONObject();
            json.put("cmd", "search");
            json.put("ics_code", ics_code);
            json.put("rank", rank);

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

                    try {
                        JSONArray jArray = new JSONArray(response);
                        if (jArray.length() == 0){
                            layout_alert.setVisibility(View.GONE);
                            txt_user.setText("");
                            new SweetAlertDialog(BalanceLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("แจ้งเตือน")
                                    .setContentText("ไม่พบ ICS Code!")
                                    .show();
                        }else {
                            for (int i = 0; i < jArray.length(); i++) {
                                NAME = jArray.getJSONObject(i).getString("Product_Name").trim();
                                CUSTOMER = jArray.getJSONObject(i).getString("Customer_Reference").trim()== "null" ? "" : jArray.getJSONObject(i).getString("Customer_Reference").trim();;
                                QTY_REEL = jArray.getJSONObject(i).getString("Qty_Reel").trim();
                                item_product_type = jArray.getJSONObject(i).getString("Type").trim();
                            }

//                            if(mc_product_type.trim().equals(item_product_type)){
                            if(map_machine.containsKey(item_product_type)){
                                Machine_Lists mc = map_machine.get(item_product_type);
                                machine_no = mc.getMachine_No();
                                mc_product_type = mc.getType();
                                printer_ip = mc.getPrinter_IP();

                                scan_rank_card = true;
                                txt_name.setText(NAME);
                                txt_rank.setText(rank);
                                txt_reel_qty.setText(QTY_REEL);
                                REQUEST_REEL_QTY = Integer.parseInt(QTY_REEL);
                                layout_alert.setVisibility(View.GONE);
                            }else{
//                                new SweetAlertDialog(BalanceLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
//                                        .setTitleText("Type mismatch")
//                                        .setContentText("Machine Type: "+mc_product_type)
//                                        .show();
                                MyAlert alert =  new MyAlert(BalanceLabel_Activity.this);
                                alert.setMessage("Type ไม่ตรงกัน!");
                                alert.show();
                                layout_alert.setVisibility(View.GONE);
                            }
                        }
                    }catch (JSONException e) {
                        layout_alert.setVisibility(View.GONE);
                        new SweetAlertDialog(BalanceLabel_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();

        }catch (JSONException e) {
            layout_alert.setVisibility(View.GONE);
            new SweetAlertDialog(BalanceLabel_Activity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage())
                    .show();
        }
    }

    private void Check_RankCard(String rank_card, String lot_no, int qty) {
        try {
            txt_message.setText("Please wait, searching data...");
            layout_alert.setVisibility(View.VISIBLE);

            JSONObject json = new JSONObject();
            json.put("cmd", "search");
            json.put("rank_card", rank_card);
            json.put("lot_no", lot_no);

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

                    try {
                        JSONArray jArray = new JSONArray(response);
                        if (jArray.length() == 0){ // no history rank card
                            QTY_RANK_CARD = qty;
                        }else {
                            String  balance = "";
                            for (int i = 0; i < jArray.length(); i++) {
                                balance = jArray.getJSONObject(i).getString("balance").trim();
                            }
                            QTY_RANK_CARD = Integer.parseInt(balance);
                        }
                        if (QTY_RANK_CARD == 0){
//                            new SweetAlertDialog(BalanceLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
//                                    .setTitleText("WARNING")
//                                    .setContentText("This Rank Card qty = 0")
//                                    .show();
                            MyAlert alert =  new MyAlert(BalanceLabel_Activity.this);
                            alert.setMessage("จำนวน Rank Card = 0");
                            alert.show();

                            scan_rank_card = false;
                            scan_lot_no = false;
                            txt_name.setText("");
                            txt_rank.setText("");
                            txt_lot_no.setText("");
                            txt_reel_qty.setText("0");
                            layout_alert.setVisibility(View.GONE);
                        }else{
                            if (QTY_RANK_CARD > REQUEST_REEL_QTY){
//                                new SweetAlertDialog(BalanceLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
//                                        .setTitleText("WARNING")
//                                        .setContentText("Qty balance > QTY/REEL")
//                                        .show();
                                MyAlert alert =  new MyAlert(BalanceLabel_Activity.this);
                                alert.setMessage("จำนวนคงเหลือ \n มากกว่า QTY/REEL");
                                alert.show();
                            }
                            txt_lot_no.setText(lot_no);
                            txt_balance.setText(String.valueOf(QTY_RANK_CARD));
                            layout_alert.setVisibility(View.GONE);
                        }
                        Log.d(getString(R.string.tag), "QTY_RANK_CARD: " + String.valueOf(QTY_RANK_CARD));
                    }catch (JSONException e) {
                        layout_alert.setVisibility(View.GONE);
                        new SweetAlertDialog(BalanceLabel_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();

        }catch (JSONException e) {
            layout_alert.setVisibility(View.GONE);
            new SweetAlertDialog(BalanceLabel_Activity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage())
                    .show();
        }
    }



    private void Check_Machine(String machine_code) {
        map_machine.clear();
        try {
            txt_message.setText("Please wait, searching data...");
            layout_alert.setVisibility(View.VISIBLE);

            JSONObject json = new JSONObject();
            json.put("cmd", "search");
            json.put("machine_code", machine_code);

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

                    try {
                        JSONArray jArray = new JSONArray(response);
                        if (jArray.length() == 0){
                            layout_alert.setVisibility(View.GONE);
                            txt_machine.setText("");
                            new SweetAlertDialog(BalanceLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("แจ้งเตือน")
                                    .setContentText("ไม่พบเครื่องจักร!")
                                    .show();
                        }else {
                            for (int i = 0; i < jArray.length(); i++) {
                                map_machine.put(jArray.getJSONObject(i).getString("Type").trim(),
                                        new Machine_Lists(
                                                jArray.getJSONObject(i).getString("Machine_No").trim(),
                                                jArray.getJSONObject(i).getString("Machine_Code").trim(),
                                                jArray.getJSONObject(i).getString("Type").trim(),
                                                jArray.getJSONObject(i).getString("Delay_min").trim(),
                                                "",
                                                jArray.getJSONObject(i).getString("Printer_IP").trim()));
//                                machine_no = jArray.getJSONObject(i).getString("Machine_No").trim();
//                                mc_product_type = jArray.getJSONObject(i).getString("Type").trim();
//                                printer_ip = jArray.getJSONObject(i).getString("Printer_IP").trim();
                            }
                            if (txt_name.getText().equals("")) {
                                txt_machine.setText(machine_code);
                                scan_machine = true;
                            }else{
                                if (map_machine.containsKey(item_product_type)){
                                    Machine_Lists mc = map_machine.get(item_product_type);
                                    machine_no = mc.getMachine_No();
                                    mc_product_type = mc.getType();
                                    printer_ip = mc.getPrinter_IP();
                                    txt_machine.setText(machine_code);
                                    scan_machine = true;
                                }else{
                                    layout_alert.setVisibility(View.GONE);
                                    MyAlert alert =  new MyAlert(BalanceLabel_Activity.this);
                                    alert.setMessage("Type ไม่ตรงกัน!");
                                    alert.show();
                                    layout_alert.setVisibility(View.GONE);
                                }
                            }
                            layout_alert.setVisibility(View.GONE);
                        }
                    }catch (JSONException e) {
                        layout_alert.setVisibility(View.GONE);
                        new SweetAlertDialog(BalanceLabel_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();

        }catch (JSONException e) {
            layout_alert.setVisibility(View.GONE);
            new SweetAlertDialog(BalanceLabel_Activity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage())
                    .show();
        }
    }

    private void Check_User(String user_id) {
        try {
            txt_message.setText("Please wait, searching data...");
            layout_alert.setVisibility(View.VISIBLE);

            JSONObject json = new JSONObject();
            json.put("cmd", "search");
            json.put("user_id", user_id);

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

                    try {
                        JSONArray jArray = new JSONArray(response);
                        if (jArray.length() == 0){
                            layout_alert.setVisibility(View.GONE);
                            txt_user.setText("");
                            new SweetAlertDialog(BalanceLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("แจ้งเตือน")
                                    .setContentText("ไม่พบรหัสพนักงาน!")
                                    .show();
                        }else {
                            txt_user.setText(user_id);
                            layout_alert.setVisibility(View.GONE);
                        }
                    }catch (JSONException e) {
                        layout_alert.setVisibility(View.GONE);
                        new SweetAlertDialog(BalanceLabel_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();

        }catch (JSONException e) {
            layout_alert.setVisibility(View.GONE);
            new SweetAlertDialog(BalanceLabel_Activity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage())
                    .show();
        }
    }

    @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 (b_print == false){
                        if (error_print == true){//print error --> print again
                            Command_Print();

                        }else {
                            Block_button();
                            Check_DataInput();
                        }
                    }
                    break;

                case P3:
                    if (error_print == false) {
                        Clear_Layout();
                    }
                    break;
            }
        }

        return super.onKeyUp(keyCode, event);
    }
}