package com.tomas.lps_asi;

import android.annotation.SuppressLint;
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.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

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 com.keyence.autoid.sdk.scan.DecodeResult;
import com.tomas.lps_asi.Adapter.Material_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.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_reel_qty, txt_message,txt_leader, txt_msg;
    EditText edt_material, edt_balance;
    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, Last_Taping_lot_no, Last_Machine_no, Current_Machine_no;
    Calendar calendar;
    EditText edt_label_qty;
    boolean scan_rank_card, scan_machine, b_print, scan_lot_no, error_print, nurse_call;
    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,layout_nurse_call;
    LinearLayout layout_balance_label;
    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");

        scan_times = 0;
        b_print = false;
        scan_machine = false;
        scan_rank_card  = false;
        scan_lot_no = false;
        stopThread = true;
        error_print = false;
        nurse_call = 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);
        layout_nurse_call = (ConstraintLayout)findViewById(R.id.layout_nurse_call);
        layout_balance_label = (LinearLayout) findViewById(R.id.layout_balance_label);

        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_user = (TextView) findViewById(R.id.txt_user_id);
        txt_machine = (TextView) findViewById(R.id.txt_machine_code);
        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_reel_qty = (TextView) findViewById(R.id.txt_reel_qty);
        txt_message = (TextView)findViewById(R.id.txt_message);
        txt_leader = (TextView) findViewById(R.id.txt_leader);
        txt_msg = (TextView)findViewById(R.id.txt_msg);

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

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

        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;
            case R.id.btn_ok_nurse_call: //23042025
                OK_NurseCall();
                break;

            case R.id.btn_cancel_nurse_call://23042025
                Cancel_NurseCall();
                break;
        }
    }

    private void Check_DataInput() {
        if (edt_label_qty.getText().toString().equals("")||edt_label_qty.getText().toString().equals("0")){
            edt_label_qty.setText("1");
        }

        if (edt_balance.getText().toString().trim().equals("")||edt_balance.getText().toString().trim().equals("0")){
            Unblock_button();
            new SweetAlertDialog(BalanceLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("แจ้งเตือน")
                    .setContentText("กรุณาใส่จำนวนคงเหลือให้ถูกต้อง")
                    .show();

        }else 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){
                Generate_Label();
            }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 Cancel_NurseCall() {
        nurse_call = false;
        layout_balance_label.setVisibility(View.VISIBLE);
        layout_nurse_call.setVisibility(View.GONE);
        txt_leader.setText("");
        Clear_Layout();
    }

    private void OK_NurseCall() {
        String str_leader = txt_leader.getText().toString().trim();
        if (str_leader.equals("")){
            new SweetAlertDialog(BalanceLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("แจ้งเตือน")
                    .setContentText("กรุณาสแกนรหัส leader!")
                    .show();
        }else {
            nurse_call = false;
            layout_balance_label.setVisibility(View.VISIBLE);
            layout_nurse_call.setVisibility(View.GONE);
        }
    }

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

        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 {
            String scan = data.trim();
            Log.d(getString(R.string.tag), "scan data : " + data);
            if (data.length() == 6 && nurse_call == true ){
                User_Lists lists = Settings.getMap_user().get(data);
                String role = lists.getRole();
                if (role.trim().equals("LEADER")){
                    txt_leader.setText(data);
                    txt_msg.setText("");
                }else {
                    txt_leader.setText("");
                    txt_msg.setText("รหัสพนักงานนี้ไม่ใช่ leader!!");
                }
            }else 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.

                if (scan.substring(0,1).trim().equals("E")){
                    RANK_CARD_LOT = scan;
                    scan_lot_no = true;
                    Check_RC_MC(RANK_CARD, RANK_CARD_LOT, item_product_type);

                }else {
                    new SweetAlertDialog(BalanceLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                            .setTitleText("แจ้งเตือน")
                            .setContentText("โปรดตรวจสอบ Lot no.!")
                            .show();
                }
            }else{
                Log.d(getString(R.string.tag), "scan else  : " + scan);

                if (scan.length() == 6) {//scan user
                    if (Settings.getMap_user().containsKey(data)){
                        User_Lists lists = Settings.getMap_user().get(data);
                        txt_user.setText(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 (scan.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(scan);
                    }
                }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("");
                        edt_balance.setText("0");
                        txt_reel_qty.setText("0");

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

            Utils.hideKeyboardFrom(getApplicationContext(), default_view);

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

    private void Check_RC_MC(String rank_card, String lot_no, String type) {//23042025
        //เป็นการเช็คว่า Rank Card นี้ ใช้กับเครื่องนี้อยู่ใช่หรือไม่
        //get สถานะเครื่องจักร ปัจจุบันว่า เดินงานกับ rankcard นี้หรือไม่ สามารถเดินต่อ หรือchange model ได้หรือไม่
        Log.d(getString(R.string.tag), "Check_RankCard : " + rank_card+"|"+lot_no+"|"+type);
        Log.d(getString(R.string.tag), "map_machine : " + map_machine.size());

        if (map_machine.containsKey(type)) {
            Log.d(getString(R.string.tag), "map_machine.containsKey if");
            Machine_Lists mc = map_machine.get(type);
            String old_rank_card = mc.getRank_card();
            String old_lot_no = mc.getLot_no();
            String balance = mc.getBalance();
            Log.d(getString(R.string.tag), old_rank_card+"|"+old_lot_no+"|"+balance);

            if(!old_rank_card.trim().equals("") && !old_lot_no.trim().equals("")) {

                if (old_rank_card.trim().equals(rank_card) && old_lot_no.trim().equals(lot_no)) {
                    Check_Balance(RANK_CARD, RANK_CARD_LOT, QTY_RANK_CARD);

                } else {
                    MyAlert alert = new MyAlert(BalanceLabel_Activity.this);
                    alert.setMessage("ไม่สามารถสแกนใบนี้กับเครื่องนี้ได้ \n กรุณาสแกน Rank Card นี้ \n" + old_rank_card + "\n" + old_lot_no);
                    alert.show();
                    Clear_Layout();
                }
            }else {
                Check_Balance(RANK_CARD, RANK_CARD_LOT, QTY_RANK_CARD);
            }

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

    private void Check_Balance(String rank_card, String lot_no, int qty) {//23042025
        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
                            layout_alert.setVisibility(View.GONE);
                            MyAlert alert =  new MyAlert(BalanceLabel_Activity.this);
                            alert.setMessage("ไม่พบ Rank Card ในระบบ");
                            alert.show();
                            Clear_Layout();//23042025
                        }else {
                            String  balance = "";
                            for (int i = 0; i < jArray.length(); i++) {
                                balance = jArray.getJSONObject(i).getString("balance").trim();
                                Last_Taping_lot_no = jArray.getJSONObject(i).getString("taping_lot_no").trim();
                                Last_Machine_no = jArray.getJSONObject(i).getString("machine_no").trim();
                            }
                            QTY_RANK_CARD = Integer.parseInt(balance);
                            Log.d(getString(R.string.tag), "QTY_RANK_CARD: " + String.valueOf(QTY_RANK_CARD));
                            Log.d(getString(R.string.tag), "Last_Taping_lot_no: " + String.valueOf(Last_Taping_lot_no));

                            if (QTY_RANK_CARD == 0){
                                MyAlert alert =  new MyAlert(BalanceLabel_Activity.this);
                                alert.setMessage("จำนวน Rank Card = 0");
                                alert.show();
                                Clear_Layout();
//                                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{
                                //เช็ค rank card ใช้ถูกเครื่องมั้ย
                                layout_alert.setVisibility(View.GONE);
                                if (Last_Machine_no.trim().equals(Current_Machine_no)) {
                                    if (QTY_RANK_CARD > REQUEST_REEL_QTY) {//23042025
                                        nurse_call = true;
                                        layout_nurse_call.setVisibility(View.VISIBLE);
                                        layout_balance_label.setVisibility(View.GONE);
                                    }
                                    txt_lot_no.setText(lot_no);
                                    edt_balance.setText(String.valueOf(QTY_RANK_CARD));
                                    layout_alert.setVisibility(View.GONE);

                                }else{
                                    MyAlert alert = new MyAlert(BalanceLabel_Activity.this);
                                    alert.setMessage("ขณะนี้ Rank Card นี้ \nถูกใช้อยู่ที่เครื่อง "+Last_Machine_no);
                                    alert.show();
                                    Clear_Layout();
                                }
                            }
                        }

                    }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_ICS_Code(String ics_code) {
        map_item.clear();
        try {
            txt_message.setText("กรุณารอสักครู่ กำลังค้นหาข้อมูล...");
            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();

                                            Current_Machine_no = machine_no;
                                            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 Generate_Label() {
        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("กรุณารอสักครู่ กำลังบันทึกข้อมูล...");

            //insert table TapingLabel
            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();
                }
            }
            JSONArray jArray_tapping_label = new JSONArray();
            Map<String, String> jsonTapingLabel = new HashMap<>();
            jsonTapingLabel.put("taping_lot_no", Last_Taping_lot_no);
            jsonTapingLabel.put("ics_code", ICS_CODE);
            jsonTapingLabel.put("product_name",  txt_name.getText().toString().trim());
            jsonTapingLabel.put("rank",  RANK);
            jsonTapingLabel.put("type",  mc_product_type);
            jsonTapingLabel.put("cust_ref", CUSTOMER);
            jsonTapingLabel.put("machine_no", machine_no);
            jsonTapingLabel.put("taping_qty", edt_balance.getText().toString().trim());
            jsonTapingLabel.put("label_qty", edt_label_qty.getText().toString().trim());
            jsonTapingLabel.put("label_type", Settings.getLabelType());
            jsonTapingLabel.put("remark", "");
            jsonTapingLabel.put("material_a", Material_a);
            jsonTapingLabel.put("material_b", Material_b);
            jsonTapingLabel.put("create_dt", dt_to_server);
            jsonTapingLabel.put("create_user_id", txt_user.getText().toString().trim());
            jsonTapingLabel.put("ref_id", "");
            JSONObject jsonObj = new JSONObject(jsonTapingLabel);
            jArray_tapping_label.put(jsonObj);

            //insert table RankCard
            JSONArray jArray_RankCard = new JSONArray();
            Map<String, String> jsParams = new HashMap<>();
            jsParams.put("rank_card", RANK_CARD);
            jsParams.put("lot_no", RANK_CARD_LOT);
            jsParams.put("type",  mc_product_type);
            jsParams.put("machine_no",machine_no );
            jsParams.put("ics_code", ICS_CODE);
            jsParams.put("product_name", txt_name.getText().toString().trim());
            jsParams.put("rank", RANK);
            jsParams.put("qty", edt_balance.getText().toString().trim());
            jsParams.put("qty_used", edt_balance.getText().toString().trim());
            jsParams.put("balance", "0");
            jsParams.put("taping_lot_no", Last_Taping_lot_no);
            jsParams.put("create_dt", dt_to_server);
            jsParams.put("ref_id", "");
            JSONObject jsObj = new JSONObject(jsParams);
            jArray_RankCard.put(jsObj);

            JSONObject json = new JSONObject();
            json.put("cmd", "generate_label");
            json.put("label_type", Settings.getLabelType());
            json.put("taping_lot_no", Last_Taping_lot_no);
            json.put("label_datas",jArray_tapping_label);
            json.put("rank_card_datas",jArray_RankCard);


            new AsyncHttpClient(getApplicationContext(),
                    Settings.getMgmtList().get("web_api")+ "/generate_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) {
                            String lot_no = jsonObject.getString("error");
                            Log.d(getString(R.string.tag), "lot_no : " + lot_no);
                            Command_Print();

                        } else {
                            Unblock_button();
                            layout_alert.setVisibility(View.GONE);
                            new SweetAlertDialog(BalanceLabel_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                    .setTitleText("ERROR")
                                    .setContentText(jsonObject.getString("error"))
                                    .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 (JSONException 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() {
        if (ICS_CODE.trim().equals("")//check data
                ||NAME.trim().equals("")
                ||edt_balance.getText().toString().trim().equals("0")
                ||Last_Taping_lot_no.trim().equals("")){

            MyAlert alert = new MyAlert(BalanceLabel_Activity.this);
            alert.setMessage("การสั่งพิมพ์เกิดข้อผิดพลาด +\n+ กรุณาติดต่อ TomasTech");
            alert.show();

            Clear_Layout();

        }else {
            layout_alert.setVisibility(View.VISIBLE);
            txt_message.setText("Printing label....");

            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|%s"
                    , ICS_CODE
                    , NAME
                    , edt_balance.getText().toString().trim()
                    , Last_Taping_lot_no
                    , CUSTOMER
                    ,"HASUU TP.");

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

        }
    }

    private void Check_Machine(String machine_code) {
        map_machine.clear();
        try {
            txt_message.setText("กรุณารอสักครู่ กำลังค้นหาข้อมูล...");
            layout_alert.setVisibility(View.VISIBLE);

            JSONObject json = new JSONObject();
//            json.put("cmd", "search");23042025
            json.put("cmd", "check_mc_rc");
            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(),
                                                jArray.getJSONObject(i).getString("rank_card").trim(),
                                                jArray.getJSONObject(i).getString("lot_no").trim(),
                                                jArray.getJSONObject(i).getString("balance").trim()));
                            }

                            scan_machine = true;
                            txt_machine.setText(machine_code);
//                            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();
        }
    }


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