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

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
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.RankCard_Adapter;
import com.tomas.lps_asi.Adapter.TapeMaterial_Adapter;
import com.tomas.lps_asi.ListData.Item_Lists;
import com.tomas.lps_asi.ListData.Machine_Lists;
import com.tomas.lps_asi.ListData.Material_Code_List;
import com.tomas.lps_asi.ListData.Material_Scan;
import com.tomas.lps_asi.ListData.RankCard_Lists;
import com.tomas.lps_asi.lib.AlertProgress;
import com.tomas.lps_asi.lib.ConvertStringToCalendar;
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.Arrays;
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 NewTapingLabel_Activity extends Scanner implements View.OnClickListener {
    TextView txt_date, txt_user_id, txt_machine,txt_qr_code_rank_card, txt_rank,txt_name, txt_classify_lot, txt_sum_qty, txt_reel_qty;
    EditText edt_label_qty;
    Calendar calendar, end_calendar, start_calendar;
    RecyclerView view_rank_card, view_material;

    AlertProgress alert;
    SimpleDateFormat date_time_fm, date_fm, date_taping_fm;
    String  str_dt_format = "yyyy-MM-dd HH:mm:ss", end_dt, start_dt, str_date, Current_RackCard, Current_Lot,
            dt_taping,ready_dt, dt_to_server, delay_time,Next_Ready_dt, machine_no, GEN_LOT_TAPING, printer_ip;
    int balance_rankcard = 0, REQUEST_REEL_QTY, QTY_RANK_CARD, LABEL_QTY, PRINT_TIMES;
    boolean error_print, b_print;
    Map<String, Material_Scan>map_material_scan;
    Map<String, Material_Code_List>map_material_list;
    Map<String, RankCard_Lists> map_rank_card;
    Map<String, Machine_Lists> map_machine;
    List<RankCard_Lists> list_rank_card;
    List<Material_Scan>list_material_scam;
    RankCard_Adapter rankCard_adapter;
    TapeMaterial_Adapter material_adapter;
    private JSONArray j_classify_rc;
    Button btn_print, btn_clear;
    ImageButton imb_back;
    private volatile boolean stopThread = true;

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

        default_view = (EditText) findViewById(R.id.txt_label_issue_tmp);
        alert = new AlertProgress(this);

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

        error_print = false;
        b_print = false;
        stopThread = true;

        map_material_scan = new LinkedHashMap<>();
        map_machine = new LinkedHashMap<>();
        map_material_list = new LinkedHashMap<>();
        map_rank_card = new LinkedHashMap<>();
        list_rank_card = new ArrayList<RankCard_Lists>();
        list_material_scam = new ArrayList<Material_Scan>();

        txt_date = (TextView)findViewById(R.id.txt_date);
        txt_user_id = (TextView) findViewById(R.id.txt_user_id);
        txt_machine = (TextView) findViewById(R.id.txt_machine);
        txt_qr_code_rank_card = (TextView) findViewById(R.id.txt_qr_code_rank_card);
        txt_rank = (TextView) findViewById(R.id.txt_rank);
        txt_name = (TextView) findViewById(R.id.txt_name);
        txt_classify_lot = (TextView) findViewById(R.id.txt_classify_lot);
        txt_sum_qty = (TextView) findViewById(R.id.txt_sum_qty);
        txt_reel_qty = (TextView) findViewById(R.id.txt_reel_qty);

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

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

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

        imb_back = (ImageButton)findViewById(R.id.imb_back);
        btn_clear = (Button)findViewById(R.id.btn_clear);
        btn_print = (Button)findViewById(R.id.btn_print);
        btn_print.setBackgroundResource(R.drawable.button_backgroup_gray);
        btn_print.setEnabled(false);




    }

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

    }

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

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

            case R.id.btn_print:
                //print
                if (b_print == false){
                    if (error_print == true){//print error --> print again
                        Command_Print();

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

    private void Block_button() {
        b_print = true;
        btn_print.setEnabled(false);
        btn_print.setBackgroundResource(R.drawable.button_backgroup_gray);
        btn_clear.setEnabled(false);
        btn_clear.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);
        btn_clear.setEnabled(true);
        btn_clear.setBackgroundResource(R.drawable.button_backgroup_yellow);
    }

    private void Clear_Layout() {
        stopThread = true;
        b_print = false;
        error_print = false;
        txt_machine.setText("");
        Current_RackCard = "";
        Current_Lot = "";
        balance_rankcard = 0;
        txt_qr_code_rank_card.setText("");
        txt_classify_lot.setText("");
        txt_name.setText("");
        txt_rank.setText("");
        txt_reel_qty.setText("0");
        j_classify_rc = null;
        map_material_scan.clear();
        map_machine.clear();
        map_material_list.clear();
        map_rank_card.clear();
        list_material_scam.clear();
        list_rank_card.clear();
        Set_View_Material_Scan();
        Set_View_RankCard();
    }

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

            if (scan.substring(0,1).trim().equals("E")){
                if (txt_qr_code_rank_card.getText().toString().trim().equals("")) {
                    new SweetAlertDialog(NewTapingLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                            .setTitleText("แจ้งเตือน")
                            .setContentText("กรุณาสแกน rank card!")
                            .show();
                    return;
                }

                txt_classify_lot.setText(data);

                if (Current_Lot.trim().equals("") && Current_RackCard.trim().equals("")){//เครื่องไม่เคยถูกใช้ ใช้ได้เลย
                    Check_Status_RC();

                }else {
                    if (txt_qr_code_rank_card.getText().toString().trim().equals(Current_RackCard)//สแกนใบเดิม
                            && txt_classify_lot.getText().toString().trim().equals(Current_Lot)){
                        if (balance_rankcard == 0) {
                            MyAlert alert = new MyAlert(NewTapingLabel_Activity.this);
                            alert.setMessage("จำนวน Rank Card = 0");
                            alert.show();
                            Clear_Layout();

                        }else {
                            Get_RankCard("old");//แสดงว่ายังมีจำนวนเหลืออยู่ เช็คจำนวนที่เหลือ เพื่อออกtaping
                        }
                    }else {
                        if (balance_rankcard == 0) {
                            SweetAlertDialog d = new SweetAlertDialog(NewTapingLabel_Activity.this, SweetAlertDialog.WARNING_TYPE);
                            d.setCancelable(false);
                            d.setTitleText("แจ้งเตือน");
                            d.setContentText("ต้องการ Change Model ใช่หรือไม่?");
                            d.setCancelText("ไม่");
                            d.setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                @Override
                                public void onClick(SweetAlertDialog sd) {
                                    sd.dismiss();
                                    Clear_Layout();
                                }
                            });
                            d.setConfirmText("ใช่");
                            d.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                @Override
                                public void onClick(SweetAlertDialog sd) {
                                    sd.dismiss();
                                    Check_Status_RC();
                                }
                            });
                            d.show();
                        }else {
                            MyAlert alert = new MyAlert(NewTapingLabel_Activity.this);
                            alert.setMessage("ไม่สามารถสแกนใบนี้กับเครื่องนี้ได้ \n กรุณาสแกน Rank Card นี้ \n"+Current_RackCard+"\n"+Current_Lot);
                            alert.show();
                            Clear_Layout();

                        }
                    }
                }
            } else if (scan.substring(0,2).trim().equals("CV")||scan.substring(0,2).trim().equals("CR")) {
                if (txt_qr_code_rank_card.getText().toString().trim().equals("")//สแกนใบเดิม
                        || txt_classify_lot.getText().toString().trim().equals("")) {
                    new SweetAlertDialog(NewTapingLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                            .setTitleText("แจ้งเตือน")
                            .setContentText("กรุณาสแกน rank card!")
                            .show();
                    return;
                }

                if (map_material_scan.containsKey(scan)) {
                    map_material_scan.remove(scan);
                    Set_View_Material_Scan();
                    //                        Set_View_Material_Scan();
                } else {
                    Check_Material_dt(scan);
                }

            }else if (scan.substring(0,2).trim().equals("TP")){
                    Check_Machine(scan);

            }else if (scan.length() == 6){
                    if (Settings.getMap_user().containsKey(scan)){
                        if (Settings.getMap_user().get(data.trim()).getTaping().trim().equals("1")){
                            txt_user_id.setText(scan);

                        }else {
                            txt_user_id.setText("");
                            new SweetAlertDialog(NewTapingLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("แจ้งเตือน")
                                    .setContentText("ไม่อนุญาตให้ทำ Taping")
                                    .show();
                        }
                    }else {
                        txt_user_id.setText("");
                        new SweetAlertDialog(NewTapingLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                .setTitleText("แจ้งเตือน")
                                .setContentText("ไม่พบรหัสพนักงาน!")
                                .show();
                    }
            }else if (scan.length() >= 20){
                    if (txt_machine.getText().toString().trim().equals("")){//check scan machine
                        new SweetAlertDialog(NewTapingLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                .setTitleText("แจ้งเตือน")
                                .setContentText("กรุณาสแกนเครื่องจักร!")
                                .show();
                    }else{
                        txt_qr_code_rank_card.setText(data);
                    }
            }else {
                    new SweetAlertDialog(NewTapingLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                            .setTitleText("แจ้งเตือน")
                            .setContentText("QR Code ไม่ถูกต้อง!")
                            .show();
            }

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

    private void Check_Material_dt(String scan) {
        String[] tokens = scan.trim().split(getString(R.string.DELIMITER_SCAN_TOKEN),-1);
        Log.d(getString(R.string.tag), Arrays.deepToString(tokens));
        if (tokens.length == 4){
            String M_Type = tokens[0];
            String M_Code = tokens[1];
            String M_lot_no = tokens[2];
            String M_Exp = tokens[3];
            try {
                Calendar now = Calendar.getInstance();
                Calendar now_dt = (Calendar) now.clone();
                Log.d(getString(R.string.tag), "now_dt: " + now_dt);
                String str_format_dt = "yyyy-MM-dd";

                Calendar exp_dt = ConvertStringToCalendar.convert(M_Exp, str_format_dt);
                String str_exp_dt = date_fm.format(exp_dt.getTime());
                Log.d(getString(R.string.tag), "str_exp_dt: " + str_exp_dt);

                if (now_dt.before(exp_dt)){
                    //check material
                    String M_Key = M_Type+M_Code;
                    String type = null;
                    Boolean check_type = false;
                    if (map_material_list.containsKey(M_Key)){
                        if (map_material_scan.size() > 0){//check duplicate material type
                            for (String key : map_material_scan.keySet()){
                                Material_Scan data = map_material_scan.get(key);
                                type = data.getMaterial_type();

                                if (type.trim().equals(M_Type)){
                                    check_type = true;
                                }
                            }
                            if (check_type == true){
                                new SweetAlertDialog(NewTapingLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                        .setTitleText("แจ้งเตือน")
                                        .setContentText("สแกน "+M_Type+" แล้ว!")
                                        .show();
                                return;
                            }
                        }

                        map_material_scan.put(scan, new Material_Scan(
                                "",
                                M_Code,
                                map_material_list.get(M_Key).getMaterial_name().trim(),
                                M_lot_no,
                                M_Type,
                                M_Exp));
                        Set_View_Material_Scan();

                    }else {
                        new SweetAlertDialog(NewTapingLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                .setTitleText("แจ้งเตือน")
                                .setContentText("ไม่พบ Material!")
                                .show();
                    }

                }else {
                    new SweetAlertDialog(NewTapingLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                            .setTitleText("แจ้งเตือน")
                            .setContentText("Material หมดอายุแล้ว!")
                            .show();
                }
            } catch (Exception e) {
                new SweetAlertDialog(NewTapingLabel_Activity.this, SweetAlertDialog.ERROR_TYPE)
                        .setTitleText("ERROR get_date")
                        .setContentText(e.getMessage())
                        .show();
            }

        }else {
            new SweetAlertDialog(NewTapingLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("แจ้งเตือน")
                    .setContentText("QR Code ไม่ถูกต้อง!")
                    .show();
        }
    }

    private void Set_View_Material_Scan() {
        list_material_scam.clear();
        for (String key : map_material_scan.keySet()){
            Material_Scan m_data = map_material_scan.get(key);
            list_material_scam.add(new Material_Scan(
                    "",
                    m_data.getMaterial_code(),
                    m_data.getMaterial_name(),
                    m_data.getMaterial_lot_no(),
                    m_data.getMaterial_type(),
                    m_data.getMaterial_exp()));
        }
        Log.d("ASI", "for list : " + list_material_scam.size());
        material_adapter = new TapeMaterial_Adapter(list_material_scam, NewTapingLabel_Activity.this);
        view_material.setAdapter(material_adapter);

        if (map_material_scan.size() == 2){
            btn_print.setEnabled(true);
            btn_print.setBackgroundResource(R.drawable.button_backgroup_green);
        }else {
            btn_print.setEnabled(false);
            btn_print.setBackgroundResource(R.drawable.button_backgroup_gray);
        }
    }

    private void Check_Status_RC() {//เช็คว่า Ranck card นี้ถูกใช้อยู่กับเครื่องไหน
        try {
            alert.setMessage("กรุณารอสักครู่ กำลังค้นหาข้อมูล...");
            alert.show();

            JSONObject json = new JSONObject();
            json.put("cmd", "search");
            json.put("rank_card", txt_qr_code_rank_card.getText().toString().trim());
            json.put("lot_no", txt_classify_lot.getText().toString().trim());

            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){ // this rank card has never been used.
                            Get_RankCard("new");

                        }else {
                            String last_mc = "";
                            for (int i = 0; i < jArray.length(); i++) {
                                 last_mc = jArray.getJSONObject(i).getString("machine_no").trim();
                            }
                            MyAlert alert = new MyAlert(NewTapingLabel_Activity.this);
                            alert.setMessage("ขณะนี้ Rank Card นี้ \nถูกใช้อยู่ที่เครื่อง "+last_mc);
                            alert.show();
                            Clear_Layout();

                        }
                        alert.dismiss();

                    }catch (JSONException e) {
                        alert.dismiss();
                        new SweetAlertDialog(NewTapingLabel_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();

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

    private void Get_RankCard(String status_rc) {
        try {
            alert.setMessage("กรุณารอสักครู่ กำลังค้นหาข้อมูล...");
            alert.show();

            JSONObject json = new JSONObject();
            if (status_rc.trim().equals("new")){
                json.put("cmd", "get_rankcard");
            }else {
                json.put("cmd", "search");
            }
            json.put("rank_card", txt_qr_code_rank_card.getText().toString().trim());
            json.put("lot_no", txt_classify_lot.getText().toString().trim());

            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 {
                        j_classify_rc = new JSONArray(response);
                        if (j_classify_rc.length() == 0){ // this rank card has never been used.
                            MyAlert alert = new MyAlert(NewTapingLabel_Activity.this);
                            alert.setMessage("ไม่พบ Rack Card นี้ในระบบ");
                            alert.show();
                            Clear_Layout();

                        }else {
                            //เช็ค type
                            String qty = "";
                            String type = j_classify_rc.getJSONObject(0).getString("type").trim();
                            String name = j_classify_rc.getJSONObject(0).getString("product_name").trim();
                            String rank = j_classify_rc.getJSONObject(0).getString("rank").trim();
                            String ics = j_classify_rc.getJSONObject(0).getString("ics_code").trim();
                            String qty_reel = j_classify_rc.getJSONObject(0).getString("Qty_Reel").trim();

                            if (status_rc.trim().equals("new")){
                                qty= j_classify_rc.getJSONObject(0).getString("qty").trim();
                            }else {
                                qty = j_classify_rc.getJSONObject(0).getString("balance").trim();
                            }

                            REQUEST_REEL_QTY = Integer.parseInt(qty_reel);
                            QTY_RANK_CARD = Integer.parseInt(qty);

                            if (qty_reel.trim().equals("0")){
                                MyAlert alert = new MyAlert(NewTapingLabel_Activity.this);
                                alert.setMessage("ไม่พบข้อมูล Item Master \n กรุณาตรวจสอบ \n" + ics+"\n"+rank);
                                alert.show();
                                Clear_Layout();

                            }else {
                                if (map_machine.containsKey(type)) {
                                    Machine_Lists mc = map_machine.get(type);
                                    delay_time = mc.getDelay_min();
                                    machine_no = mc.getMachine_No();
                                    printer_ip = mc.getPrinter_IP();

                                    txt_name.setText(name);
                                    txt_rank.setText(rank);
                                    txt_reel_qty.setText(qty_reel);
                                    Get_material();
                                    Calculate_Qty();

                                } else {
                                    MyAlert alert = new MyAlert(NewTapingLabel_Activity.this);
                                    alert.setMessage("Type ไม่ตรงกัน! \n ICS Type : " + type);
                                    alert.show();
                                    Clear_Layout();
                                }
                            }
                        }
                        alert.dismiss();

                    }catch (JSONException e) {
                        alert.dismiss();
                        new SweetAlertDialog(NewTapingLabel_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();

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

    private void Calculate_Qty() {
        int BALANCE_RANK_CARD = 0;
            if (QTY_RANK_CARD > REQUEST_REEL_QTY) {
                BALANCE_RANK_CARD = (QTY_RANK_CARD - REQUEST_REEL_QTY);
                AddMap_RankCard(BALANCE_RANK_CARD);

            } else if (QTY_RANK_CARD == REQUEST_REEL_QTY) {
                AddMap_RankCard(0);

            } else {//QTY_RANK_CARD < int_QTY_REEL
                    MyAlert alert =  new MyAlert(NewTapingLabel_Activity.this);
                    alert.setMessage("มีจำนวนไม่พอ Taping"+"\n"+"กรุณาพิมพ์ใบเศษ");
                    alert.next_activity(true);
                    alert.show();
            }
    }

    private void AddMap_RankCard(int balance_rc) {
        map_rank_card.clear();
        String rc = txt_qr_code_rank_card.getText().toString().trim();
        String lot = txt_classify_lot.getText().toString().trim();
        map_rank_card.put(rc+lot, new RankCard_Lists(
                rc,
                lot,
                String.valueOf(REQUEST_REEL_QTY) ,
                String.valueOf(QTY_RANK_CARD),
                String.valueOf(balance_rc)));
        Log.d(getString(R.string.tag), "AddMap_RankCard: " + map_rank_card.size());

        Set_View_RankCard();
    }

    private void Set_View_RankCard() {
        list_rank_card.clear();

            int sum_qty = 0, int_qty = 0;
            for (String key : map_rank_card.keySet()){
                RankCard_Lists card_lists = map_rank_card.get(key);
                list_rank_card.add(new RankCard_Lists(
                        card_lists.getRankCard(),
                        card_lists.getLotNo(),
                        card_lists.getQty_Used(),
                        card_lists.getQty_RankCard(),
                        card_lists.getBalance_RankCard()
                ));

                int_qty = Integer.parseInt(card_lists.getQty_Used());
                sum_qty = (sum_qty + int_qty);
            }
        txt_sum_qty.setText(String.valueOf(sum_qty));
        rankCard_adapter = new RankCard_Adapter(list_rank_card, NewTapingLabel_Activity.this);
        view_rank_card.setAdapter(rankCard_adapter);
    }

    private void Get_material() {
        map_material_list.clear();
        try {
            alert.setMessage("กรุณารอสักครู่ กำลังค้นหาข้อมูล...");
            alert.show();

            JSONObject json = new JSONObject();
            json.put("cmd", "search");
            json.put("ics_code", j_classify_rc.getJSONObject(0).getString("ics_code").trim());

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

                            Clear_Layout();
                            new SweetAlertDialog(NewTapingLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("แจ้งเตือน")
                                    .setContentText("ไม่พบ material! \n กรุณาแจ้ง Leader")
                                    .show();
                        }else {
                            for (int i = 0; i < jArray.length(); i++) {
                                map_material_list.put(jArray.getJSONObject(i).getString("material_type").trim()+jArray.getJSONObject(i).getString("material_code").trim(),
                                        new Material_Code_List(
                                                jArray.getJSONObject(i).getString("material_code").trim(),
                                                jArray.getJSONObject(i).getString("material_name").trim(),
                                                jArray.getJSONObject(i).getString("material_type").trim()));
                            }
                            Log.d(getString(R.string.tag), "map_material_list: " + map_material_list.size());

                        }
                        alert.dismiss();
                    }catch (JSONException e) {
                        alert.dismiss();
                        new SweetAlertDialog(NewTapingLabel_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();

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

    private void Check_Machine(String machine_code) {
        map_machine.clear();
        try {
            alert.setMessage("กรุณารอสักครู่ กำลังค้นหาข้อมูล...");
            alert.show();

            JSONObject json = new JSONObject();
            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){
                            alert.dismiss();
                            txt_machine.setText("");
                            new SweetAlertDialog(NewTapingLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("แจ้งเตือน")
                                    .setContentText("ไม่พบเครื่องจักร!")
                                    .show();
                        }else {
                            alert.dismiss();
                            for (int i = 0; i < jArray.length(); i++) {
                                String Ready_dt_db = jArray.getJSONObject(i).getString("Ready_dt").trim()== "null" ? "" : jArray.getJSONObject(i).getString("Ready_dt").trim();
                                if (Ready_dt_db.trim().equals("")){
                                    ready_dt = "";
                                }else {
                                    JSONObject obj = jArray.getJSONObject(i);
                                    JSONObject array_ready_dt = obj.getJSONObject("Ready_dt");
                                    ready_dt = array_ready_dt.getString("date");
                                    ready_dt = ready_dt.substring(0, 19);
                                }

                                if(!ready_dt.trim().equals("")) {
                                    Calendar c_ready_dt= ConvertStringToCalendar.convert(ready_dt, str_dt_format);
                                    String str_ready_dt = date_time_fm.format(c_ready_dt.getTime());
                                    Log.d(getString(R.string.tag), "str_ready_dt: " + str_ready_dt.toString());

                                    Calendar now = Calendar.getInstance();
                                    Calendar now_dt = (Calendar) now.clone();
                                    String str_now = date_time_fm.format(now_dt.getTime());
                                    Log.d(getString(R.string.tag), "now_dt: " + str_now);

                                    if (now_dt.after(c_ready_dt)) {
                                        txt_machine.setText(machine_code);

                                    } else {
                                        txt_machine.setText("");
                                        MyAlert alert =  new MyAlert(NewTapingLabel_Activity.this);
                                        alert.setMessage("เครื่องจักรกำลังทำงาน"+"\n"+"จะพร้อมใช้งานเวลา \n\n"+ready_dt);
                                        alert.show();
                                        return;
                                    }
                                }else {//first time machine working
                                    txt_machine.setText(machine_code);
                                }

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

                                Current_RackCard = jArray.getJSONObject(i).getString("rank_card").trim();
                                Current_Lot = jArray.getJSONObject(i).getString("lot_no").trim();
                                balance_rankcard = Integer.parseInt(jArray.getJSONObject(i).getString("balance").trim());
                            }
                            Log.d(getString(R.string.tag), "Current Data: "+"|"+Current_RackCard+"|"+Current_Lot+"|"+balance_rankcard);
                        }
                    }catch (JSONException e) {
                        alert.dismiss();
                        new SweetAlertDialog(NewTapingLabel_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();

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

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

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

        if (map_rank_card.size() == 0){
            Unblock_button();
            new SweetAlertDialog(NewTapingLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("แจ้งเตือน")
                    .setContentText("กรุณาสแกน Rank Card!")
                    .show();
        }else{
                if (txt_user_id.getText().toString().trim().equals("")){
                    Unblock_button();
                    new SweetAlertDialog(NewTapingLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                            .setTitleText("แจ้งเตือน")
                            .setContentText("กรุณาสแกนรหัสพนักงาน!")
                            .show();
                }else{
                    //check_material
                    Boolean CR = false, CV = false;
                    for (String K : map_material_scan.keySet()){
                        Material_Scan data = map_material_scan.get(K);
                        String type = data.getMaterial_type();

                        if (type.trim().equals("CR")){
                            CR = true;
                        }else if (type.trim().equals("CV")){//CV
                            CV = true;
                        }
                    }

                    if (CV == true && CR == true) {
                        Generate_Label();

                    }else {
                        Unblock_button();
                        MyAlert alert =  new MyAlert(NewTapingLabel_Activity.this);
                        alert.setMessage("ยังสแกน material ไม่ครบ!");
                        alert.show();
                    }
                }
        }
    }

    private void Generate_Label() {
        //get start_dt end_dt
        start_calendar = Calendar.getInstance();
        end_calendar = Calendar.getInstance();
        //date gen lot
        calendar = Calendar.getInstance();
        calendar = (Calendar) calendar.clone();
        try {//check date time before 8:00AM
            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)) {
                Log.d("get_start_dt", "before" );

                start_calendar.add(Calendar.DATE, -1);
                start_dt = date_fm.format(start_calendar.getTime());

                calendar.add(Calendar.DATE, -1);
                dt_taping = date_taping_fm.format(calendar.getTime());

                end_dt = date_fm.format(end_calendar.getTime());

            }else{
                Log.d("get_start_dt", "after" );
                end_calendar.add(Calendar.DATE, +1);
                end_dt = date_fm.format(end_calendar.getTime());

                start_dt = date_fm.format(start_calendar.getTime());
                dt_taping = date_taping_fm.format(calendar.getTime());

            }
        } catch (ParseException e) {
            // Invalid date was entered
            Unblock_button();
            new SweetAlertDialog(NewTapingLabel_Activity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR get_date")
                    .setContentText(e.getMessage())
                    .show();
        }

        start_dt = start_dt + " 08:00:00";
        end_dt = end_dt + " 07:59:59";

        Log.d(getString(R.string.tag), "start_dt: " + start_dt);
        Log.d(getString(R.string.tag), "end_dt: " + end_dt);
        Log.d(getString(R.string.tag), "dt_taping: " + dt_taping);//yyyyMMdd

        String year, month, date;//date for gen lot
        year = dt_taping.substring(3,4);
        month =  dt_taping.substring(4,6);
        date = dt_taping.substring(6,8);

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


        calendar.add(Calendar.MINUTE, Integer.parseInt(delay_time));
        Next_Ready_dt = date_time_fm.format(calendar.getTime());
        Log.d(getString(R.string.tag), "Ready_dt : " + Next_Ready_dt);


        try {
            alert.setMessage("กรุณารอสักครู่ กำลังค้นหาข้อมูล...");
            alert.show();
            //for insert taping_lot
            JSONArray jArray_tapping_lot = new JSONArray();
            Map<String, String> jsonParams = new HashMap<>();
            jsonParams.put("machine_code", txt_machine.getText().toString().trim());
            jsonParams.put("machine_no", machine_no);
            jsonParams.put("taping_lot","");
            jsonParams.put("type", j_classify_rc.getJSONObject(0).getString("type").trim());
            jsonParams.put("create_user_id", txt_user_id.getText().toString().trim());
            jsonParams.put("create_dt", dt_to_server);
            JSONObject jsonObj = new JSONObject(jsonParams);
            jArray_tapping_lot.put(jsonObj);

            //insert table TapingLabel
            JSONArray jArray_tapping_label = new JSONArray();
            Map<String, String> jsonTapingLabel = new HashMap<>();
            jsonTapingLabel.put("taping_lot_no", "");
            jsonTapingLabel.put("ics_code", j_classify_rc.getJSONObject(0).getString("ics_code").trim());
            jsonTapingLabel.put("product_name",  j_classify_rc.getJSONObject(0).getString("product_name").trim());
            jsonTapingLabel.put("rank",   j_classify_rc.getJSONObject(0).getString("rank").trim());
            jsonTapingLabel.put("type",   j_classify_rc.getJSONObject(0).getString("type").trim());
            jsonTapingLabel.put("cust_ref", j_classify_rc.getJSONObject(0).getString("Customer_Reference").trim());
            jsonTapingLabel.put("machine_no", machine_no);
            jsonTapingLabel.put("taping_qty", txt_sum_qty.getText().toString().trim());
            jsonTapingLabel.put("label_qty", edt_label_qty.getText().toString().trim());
            jsonTapingLabel.put("label_type", Settings.getLabelType());
            jsonTapingLabel.put("remark", "");
            jsonTapingLabel.put("create_dt", dt_to_server);
            jsonTapingLabel.put("create_user_id", txt_user_id.getText().toString().trim());
            jsonTapingLabel.put("ref_id", "");
            JSONObject jsonObjTL = new JSONObject(jsonTapingLabel);
            jArray_tapping_label.put(jsonObjTL);

            //insert table RankCard
            JSONArray jArray_RankCard = new JSONArray();
            for (String key : map_rank_card.keySet()){
                RankCard_Lists lists = map_rank_card.get(key);

                Map<String, String> jsParams = new HashMap<>();
                jsParams.put("rank_card", lists.getRankCard());
                jsParams.put("lot_no", lists.getLotNo());
                jsParams.put("machine_no",machine_no );//23042025
                jsParams.put("classify_machine_no",j_classify_rc.getJSONObject(0).getString("classify_machine_no").trim());//23042025
                jsParams.put("type",  j_classify_rc.getJSONObject(0).getString("type").trim());//23042025
                jsParams.put("ics_code", j_classify_rc.getJSONObject(0).getString("ics_code").trim());
                jsParams.put("product_name", j_classify_rc.getJSONObject(0).getString("product_name").trim());
                jsParams.put("rank", j_classify_rc.getJSONObject(0).getString("rank").trim());
                jsParams.put("qty", lists.getQty_RankCard());
                jsParams.put("qty_used", lists.getQty_Used());
                jsParams.put("balance", lists.getBalance_RankCard());
                jsParams.put("taping_lot_no", "");
                jsParams.put("create_dt", dt_to_server);
                jsParams.put("ref_id", "");
                JSONObject jsObj = new JSONObject(jsParams);
                jArray_RankCard.put(jsObj);
            }

            //insert table MaterialFactorList
            JSONArray jArray_Material = new JSONArray();
            for (String key : map_material_scan.keySet()){
                Material_Scan lists = map_material_scan.get(key);

                Map<String, String> jsParams = new HashMap<>();
                jsParams.put("taping_lot_no", "");
                jsParams.put("material_code", lists.getMaterial_code());
                jsParams.put("material_name", lists.getMaterial_name());
                jsParams.put("material_lot_no", lists.getMaterial_lot_no());
                jsParams.put("material_type", lists.getMaterial_type());
                jsParams.put("material_exp", lists.getMaterial_exp());
                jsParams.put("create_dt", dt_to_server);
                jsParams.put("create_user_id",txt_user_id.getText().toString().trim() );
                JSONObject jsObj = new JSONObject(jsParams);
                jArray_Material.put(jsObj);
            }

            JSONObject json = new JSONObject();
            json.put("cmd", "generate_label");
            json.put("label_type", Settings.getLabelType());
            json.put("machine_no",machine_no );
            json.put("rank",  j_classify_rc.getJSONObject(0).getString("rank").trim());
            json.put("start_dt",start_dt );
            json.put("end_dt",end_dt );
            json.put("Ready_dt",Next_Ready_dt);
            json.put("year",year);
            json.put("month",month);
            json.put("date",date);
            json.put("tap_datas",jArray_tapping_lot);
            json.put("label_datas",jArray_tapping_label);
            json.put("rank_card_datas",jArray_RankCard);
            json.put("material_datas",jArray_Material);

            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) {
                            GEN_LOT_TAPING = jsonObject.getString("error");
                            Log.d(getString(R.string.tag), "GEN_LOT_TAPING : " + GEN_LOT_TAPING);
                            Command_Print();

                        } else {
                            alert.dismiss();
                            Unblock_button();
                            new SweetAlertDialog(NewTapingLabel_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                    .setTitleText("ERROR")
                                    .setContentText(jsonObject.getString("error"))
                                    .show();
                        }

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

    private void Command_Print() {
        if (GEN_LOT_TAPING.trim().equals("")){

            MyAlert alert = new MyAlert(NewTapingLabel_Activity.this);
            alert.setMessage("การสั่งพิมพ์เกิดข้อผิดพลาด +\n+ กรุณาแจ้ง LEADER +\n+ เพื่อสั่งพิมพ์ defective label");
            alert.show();

            txt_user_id.setText("");
            Clear_Layout();

        }else {
            alert.setMessage("Printing label....");
            alert.show();

            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"
                    ,  j_classify_rc.getJSONObject(0).getString("ics_code").trim()
                    ,  j_classify_rc.getJSONObject(0).getString("product_name").trim()
                    ,  j_classify_rc.getJSONObject(0).getString("Qty_Reel").trim()
                    , GEN_LOT_TAPING
                    , j_classify_rc.getJSONObject(0).getString("Customer_Reference").trim()
                    ,"");

            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) {
                            alert.dismiss();
                            Toast.makeText(NewTapingLabel_Activity.this, "Print : OK", Toast.LENGTH_SHORT).show();
                            new SweetAlertDialog(NewTapingLabel_Activity.this, SweetAlertDialog.SUCCESS_TYPE)
                                    .setTitleText("SUCCESS")
                                    .setContentText("Print : OK")
                                    .show();
                            txt_user_id.setText("");
                            Clear_Layout();
                        }

                    } else {
                        error_print = true;
                        alert.dismiss();
                        Unblock_button();
                        new SweetAlertDialog(NewTapingLabel_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());
        }
    }


    @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:
                    imb_back.performClick();
                    break;
                case P2:
                    btn_print.performClick();
                    break;
                case P3:
                    btn_clear.performClick();
                    break;

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