package com.tomas.lps_asi;

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

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

import com.keyence.autoid.sdk.scan.DecodeResult;
import com.tomas.lps_asi.Adapter.RankCard_Adapter;
import com.tomas.lps_asi.ListData.Item_Lists;
import com.tomas.lps_asi.ListData.Machine_Lists;
import com.tomas.lps_asi.ListData.RankCard_Lists;
import com.tomas.lps_asi.ListData.User_Lists;
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.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 TapingLabel_Activity extends Scanner implements View.OnClickListener {
    ConstraintLayout layout_alert;
    RankCard_Adapter rankCard_adapter;
    TextView txt_date, txt_user, txt_machine, txt_model_name, txt_rank, txt_lot_no, txt_sum_qty, txt_reel_qty, txt_message;
    EditText edt_label_qty;
    RecyclerView view_rank_card;
    Calendar calendar, end_calendar, start_calendar;
    Map<String, Machine_Lists>map_machine;
    Map<String, Item_Lists> map_item;
    SimpleDateFormat date_time_fm, date_fm, date_taping_fm;
    String str_date, create_user_id, machine_no, mc_product_type, delay_time, ready_dt,ics_code, rank, dt_to_server,
            item_product_type,RANK_CARD, RANK_CARD_LOT, ICS_CODE1, RANK1, NAME, CUSTOMER, QTY_REEL, GEN_LOT_TAPING, dt_taping,
            Machine_Job_No, printer_ip;
    String  str_dt_format = "yyyy-MM-dd HH:mm:ss", end_dt, start_dt;
    int QTY_RANK_CARD, QTY_REEL_USED, BALANCE_RANK_CARD, SUM_QTY, REQUEST_REEL_QTY, LABEL_QTY, PRINT_TIMES,DIGIT;
    boolean scan_rank_card, scan_machine, b_print, error_print, new_rank_card;
    Button btn_print;

    Map<String, RankCard_Lists> map_rank_card;
    List<RankCard_Lists> list_rank_card;
    private volatile boolean stopThread = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tabping_label);
        default_view = (EditText) findViewById(R.id.txt_label_issue_tmp);
        calendar = Calendar.getInstance();
        date_time_fm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        date_fm = new SimpleDateFormat("yyyy-MM-dd");
        date_taping_fm = new SimpleDateFormat("yyyyMMdd");
//        str_date = date_fm.format(calendar.getTime());

        scan_rank_card = false;
        scan_machine = false;
        b_print = false;
        error_print = false;
        stopThread = true;
        new_rank_card = false;

        map_machine = new LinkedHashMap<>();
        map_rank_card = new LinkedHashMap<>();
        map_item = new LinkedHashMap<>();
        list_rank_card = new ArrayList<RankCard_Lists>();

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

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

        txt_date = (TextView) findViewById(R.id.txt_date);
//        txt_date.setText(str_date);

        txt_user = (TextView) findViewById(R.id.txt_user);
        txt_machine = (TextView) findViewById(R.id.txt_machine);
        txt_model_name = (TextView) findViewById(R.id.txt_model_name);
        txt_rank = (TextView) findViewById(R.id.txt_rank);
        txt_lot_no = (TextView) findViewById(R.id.txt_lot_no);
        txt_sum_qty = (TextView) findViewById(R.id.txt_sum_qty);
        txt_reel_qty = (TextView) findViewById(R.id.txt_reel_qty);
        txt_message = (TextView)findViewById(R.id.txt_message);

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

    }

    @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 processData(String data, DecodeResult.Result result, String codeType) {
        if (data.trim().equals(""))
            return;

        if (error_print == true)
            return;

        try {
            Log.d(getString(R.string.tag), "scan data : " + data);
            if (scan_rank_card == true){//scan lot no. of rank card
                if (data.length() > 13){
                    new SweetAlertDialog(TapingLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                            .setTitleText("แจ้งเตือน")
                            .setContentText("โปรดตรวสอบ Lot no.!")
                            .show();
                }else {
                    RANK_CARD_LOT = data;
                    String Key = RANK_CARD + RANK_CARD_LOT;

                    if (map_rank_card.containsKey(Key)) {
                        map_rank_card.remove(Key);
                        Set_View_RankCard();

                    } else {
                        txt_lot_no.setText(RANK_CARD_LOT);
                        Check_Balance(RANK_CARD, RANK_CARD_LOT, QTY_RANK_CARD);
                        scan_rank_card = false;
                        txt_model_name.setTextColor(Color.parseColor("#8A8888"));
                        txt_rank.setTextColor(Color.parseColor("#8A8888"));
                    }
                }
            }else {
                if (data.length() == 6) {//scan user
//                    Check_User(data);
                    if (Settings.getMap_user().containsKey(data)){
                        create_user_id = data;
                        txt_user.setText(create_user_id);

                        User_Lists lists = Settings.getMap_user().get(data);
                        String nameEng = lists.getNameEng();
                        Log.d(getString(R.string.tag), "nameEng : " + nameEng);

                    }else {
                        txt_user.setText("");
                        new SweetAlertDialog(TapingLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                .setTitleText("แจ้งเตือน")
                                .setContentText("ไม่พบรหัสพนักงาน!")
                                .show();
                    }
                } else if (data.substring(0,2).trim().equals("TP") ) {//scan machine

                    Check_Machine(data);

                }else {//scan rank card or another.
                    txt_lot_no.setText("");
                    if (txt_machine.getText().toString().trim().equals("")){//check scan machine
                        new SweetAlertDialog(TapingLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                .setTitleText("แจ้งเตือน")
                                .setContentText("กรุณาสแกนเครื่องจักร!")
                                .show();
                    }else{
                        int sum_qty, qty_reel;
                        String sum = txt_sum_qty.getText().toString().trim();
                        sum_qty = Integer.parseInt(sum);
                        String reel = txt_reel_qty.getText().toString().trim();
                        qty_reel = Integer.parseInt(reel);
                        Log.d(getString(R.string.tag), "if: " + sum+"|"+reel);

                        if (sum_qty > 0 && sum_qty == qty_reel){
                            MyAlert alert =  new MyAlert(TapingLabel_Activity.this);
                            alert.setMessage("จำนวนครบแล้ว");
                            alert.show();

                        }else {
                            RANK_CARD = data.trim();
                            ics_code = data.trim().substring(0, 10);
                                Check_ICS_Code(ics_code);
                        }
                    }
                }
//                else if (data.length() == 20 || data.length() == 23) {//scan rank card
//                    txt_lot_no.setText("");
//                    if (txt_machine.getText().toString().trim().equals("")){//check scan machine
//                        new SweetAlertDialog(TapingLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
//                                .setTitleText("แจ้งเตือน")
//                                .setContentText("กรุณาสแกนเครื่องจักร!")
//                                .show();
//                    }else{
//                        int sum_qty, qty_reel;
//                        String sum = txt_sum_qty.getText().toString().trim();
//                        sum_qty = Integer.parseInt(sum);
//                        String reel = txt_reel_qty.getText().toString().trim();
//                        qty_reel = Integer.parseInt(reel);
//                        Log.d(getString(R.string.tag), "if: " + sum+"|"+reel);
//
//                        if (sum_qty > 0 && sum_qty == qty_reel){
////                            new SweetAlertDialog(TapingLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
////                                    .setTitleText("WARNING")
////                                    .setContentText("QTY/REEL complete")
////                                    .show();
//
//                            MyAlert alert =  new MyAlert(TapingLabel_Activity.this);
//                            alert.setMessage("จำนวนครบแล้ว");
//                            alert.show();
//
//                        }else{
//                            RANK_CARD = data.trim();
//                            ics_code = RANK_CARD.substring(0, 10);
//
//                            String qty = "";
//                            if (RANK_CARD.length() == 20) {
//                                rank = RANK_CARD.substring(10, 15);
//                                qty = RANK_CARD.substring(15, 20);
//
//                            } else {
//                                rank = RANK_CARD.substring(10, 18);
//                                qty = RANK_CARD.substring(18, 23);
//                            }
//                            QTY_RANK_CARD = Integer.parseInt(qty);
//
//
//                            if (map_rank_card.size() == 0) {//first rank card
//                                Check_Item(ics_code, rank);
//
//                            } else {
//                                if (ics_code.trim().equals(ICS_CODE1) && rank.trim().equals(RANK1)) {
//                                    txt_model_name.setTextColor(Color.parseColor("#FF000000"));
//                                    txt_rank.setTextColor(Color.parseColor("#FF000000"));
//                                    scan_rank_card = true;
//                                } else {
////                                    new SweetAlertDialog(TapingLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
////                                            .setTitleText("WARNING")
////                                            .setContentText("ICSCode or Rank mismatch!")
////                                            .show();
//                                    MyAlert alert =  new MyAlert(TapingLabel_Activity.this);
//                                    alert.setMessage("ICS Code หรือ Rank ไม่ตรงกัน!");
//                                    alert.show();
//                                }
//                            }
//                        }
//                    }
//                }else {
//                    new SweetAlertDialog(TapingLabel_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_ICS_Code(String ics_code) {
        map_item.clear();
        try {
            txt_message.setText("Please wait, searching data...");
            layout_alert.setVisibility(View.VISIBLE);

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

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

                    try {
                        JSONArray jArray = new JSONArray(response);
                        if (jArray.length() == 0){
                            layout_alert.setVisibility(View.GONE);
                            new SweetAlertDialog(TapingLabel_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");
                                String KEY = jArray.getJSONObject(i).getString("ICS_Code").trim()+jArray.getJSONObject(i).getString("Rank").trim();
                                Log.d(getString(R.string.tag), "KEY: " + KEY);
                                map_item.put(KEY,
                                        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));

                                if (map_rank_card.size() == 0) {//first 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();
                                            delay_time = mc.getDelay_min();
                                            printer_ip = mc.getPrinter_IP();
                                            ready_dt = mc.getReady_dt();

                                            Check_MC_Ready(ready_dt, mc.getMachine_Code());

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

                                        }
                                    } else {
                                        new SweetAlertDialog(TapingLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                                .setTitleText("แจ้งเตือน")
                                                .setContentText("ไม่พบ Rank : " + rank)
                                                .show();
                                    }
                                }else{//more one rank card
                                    if (ics_code.trim().equals(ICS_CODE1) && rank.trim().equals(RANK1)) {
                                        txt_model_name.setTextColor(Color.parseColor("#FF000000"));
                                        txt_rank.setTextColor(Color.parseColor("#FF000000"));
                                        scan_rank_card = true;
                                    } else {
                                        MyAlert alert =  new MyAlert(TapingLabel_Activity.this);
                                        alert.setMessage("ICS Code หรือ Rank ไม่ตรงกัน!");
                                        alert.show();
                                    }
                                }
                            }catch (Exception e){
                                layout_alert.setVisibility(View.GONE);
                                new SweetAlertDialog(TapingLabel_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                        .setTitleText("ERROR")
                                        .setContentText("sub string rank card error!")
                                        .show();
                            }
                        }
                    }catch (JSONException e) {
                        layout_alert.setVisibility(View.GONE);
                        new SweetAlertDialog(TapingLabel_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();

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

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

            case R.id.btn_clear:
                //clear list rank card
                if (error_print == false) {
                    map_rank_card.clear();
                    Set_View_RankCard();
                    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 Check_DataInput() {
        int sum_qty, qty_reel;
        String sum = txt_sum_qty.getText().toString().trim();
        sum_qty = Integer.parseInt(sum);
        String reel = txt_reel_qty.getText().toString().trim();
        qty_reel = Integer.parseInt(reel);
        Log.d(getString(R.string.tag), "if: " + sum+"|"+reel);


        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(TapingLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("แจ้งเตือน")
                    .setContentText("กรุณาสแกน Rank Card!")
                    .show();
        }else{
            if (sum_qty == qty_reel){
                if (txt_user.getText().toString().trim().equals("")){
                    Unblock_button();
                    new SweetAlertDialog(TapingLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                            .setTitleText("แจ้งเตือน")
                            .setContentText("กรุณาสแกนรหัสพนักงาน!")
                            .show();
                }else{
                    Gen_Lot_Taping();
                }
            } else {
                Unblock_button();
//                new SweetAlertDialog(TapingLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
//                        .setTitleText("WARNING")
//                        .setContentText("Qty isn't complete!")
//                        .show();
                MyAlert alert =  new MyAlert(TapingLabel_Activity.this);
                alert.setMessage("จำนวนยังไม่ครบ!");
                alert.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 Gen_Lot_Taping() {
        GEN_LOT_TAPING = "";
        //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();
            layout_alert.setVisibility(View.GONE);
            new SweetAlertDialog(TapingLabel_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;
        year = dt_taping.substring(3,4);
        month =  dt_taping.substring(4,6);
        date = dt_taping.substring(6,8);

        try {
            layout_alert.setVisibility(View.VISIBLE);
            txt_message.setText("Please wait, Generate lot no...");

            JSONObject json = new JSONObject();
            json.put("cmd", "get_job");
            json.put("machine_no",machine_no );
            json.put("start_dt",start_dt );
            json.put("end_dt",end_dt );

            new AsyncHttpClient(getApplicationContext(),
                    Settings.getMgmtList().get("web_api")+ "/taping_lot.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);
                            for (int i = 0; i < jArray.length(); i++) {
                                Machine_Job_No = jArray.getJSONObject(i).getString("mc_job_no").trim();
                            }

                            GEN_LOT_TAPING = "E" + year + month + date + Machine_Job_No + machine_no + RANK1;
                            Log.d(getString(R.string.tag), "GEN_LOT_TAPING: " + GEN_LOT_TAPING);
                            layout_alert.setVisibility(View.GONE);

                            Insert_TapingLot();

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

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

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

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

            Map<String, String> jsonParams = new HashMap<>();
            jsonParams.put("machine_code", txt_machine.getText().toString().trim());
            jsonParams.put("machine_no", machine_no);
            jsonParams.put("taping_lot",GEN_LOT_TAPING);
            jsonParams.put("type", mc_product_type);
            jsonParams.put("create_user_id", txt_user.getText().toString().trim());
            jsonParams.put("create_dt", dt_to_server);
            JSONObject jsonObj = new JSONObject(jsonParams);
            jsonArray.put(jsonObj);

            json.put("tap_datas",jsonArray);

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

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

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

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

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

            Map<String, String> jsonParams = new HashMap<>();
            jsonParams.put("taping_lot_no", GEN_LOT_TAPING);
            jsonParams.put("ics_code", ICS_CODE1);
            jsonParams.put("product_name",  txt_model_name.getText().toString().trim());
            jsonParams.put("rank",  RANK1);
            jsonParams.put("type",  mc_product_type);
            jsonParams.put("cust_ref", CUSTOMER);
            jsonParams.put("machine_no", machine_no);
            jsonParams.put("taping_qty", txt_sum_qty.getText().toString().trim());
            jsonParams.put("label_qty", edt_label_qty.getText().toString().trim());
            jsonParams.put("label_type", Settings.getLabelType());
            jsonParams.put("remark", "");
            jsonParams.put("create_dt", dt_to_server);
            jsonParams.put("create_user_id", txt_user.getText().toString().trim());
            JSONObject jsonObj = new JSONObject(jsonParams);
            jsonArray.put(jsonObj);

            json.put("label_datas",jsonArray);

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

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

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

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

            JSONObject json = new JSONObject();
            json.put("cmd", "add");
            JSONArray jsonArray = new JSONArray();
            for (String key : map_rank_card.keySet()){
                RankCard_Lists lists = map_rank_card.get(key);

                Map<String, String> jsonParams = new HashMap<>();
                jsonParams.put("rank_card", lists.getRankCard());
                jsonParams.put("lot_no", lists.getLotNo());
                jsonParams.put("ics_code", ICS_CODE1);
                jsonParams.put("product_name", txt_model_name.getText().toString().trim());
                jsonParams.put("rank", RANK1);
                jsonParams.put("qty", lists.getQty_RankCard());
                jsonParams.put("qty_used", lists.getQty_Used());
                jsonParams.put("balance", lists.getBalance_RankCard());
                jsonParams.put("taping_lot_no", GEN_LOT_TAPING);
                jsonParams.put("create_dt", dt_to_server);
                JSONObject jsonObj = new JSONObject(jsonParams);
                jsonArray.put(jsonObj);
            }
            json.put("rank_card_datas",jsonArray);

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

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


    private void Update_Machine() {
        calendar = Calendar.getInstance();
        calendar = (Calendar) calendar.clone();
        Log.d(getString(R.string.tag), "dt_to_server : " + calendar);
        calendar.add(Calendar.MINUTE, Integer.parseInt(delay_time));
        dt_to_server = date_time_fm.format(calendar.getTime());
        Log.d(getString(R.string.tag), "dt_to_server : " + dt_to_server);

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

            JSONObject json = new JSONObject();
            json.put("cmd", "update");
            json.put("Machine_No", machine_no);
            json.put("Ready_dt",dt_to_server);

            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 {
                        JSONObject jsonObject = new JSONObject(response);
                        String status = jsonObject.getString("status");
                        int affected_rows = jsonObject.getInt("affected_rows");
                        if (status.equals("success") && affected_rows > 0) {
                            Command_Print();

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

    private void Command_Print() {
        if (ICS_CODE1.trim().equals("")//check data
                ||txt_model_name.getText().toString().trim().equals("")
                ||txt_sum_qty.getText().toString().trim().equals("0")
                ||GEN_LOT_TAPING.trim().equals("")){

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

            txt_user.setText("");
            Clear_Layout();

        }else {
            layout_alert.setVisibility(View.VISIBLE);
            txt_message.setText("Send printing data....");

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

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


    class ExampleRunnable implements Runnable {

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

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


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

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

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

        String err_msg = "";
        try {
            err_msg = "Server connection failed!\nPlease contact leader.";
            String payload = String.format(
                    "%s|%s|%s|%s|%s|%s"
                    , ICS_CODE1
                    , txt_model_name.getText().toString().trim()
                    , txt_sum_qty.getText().toString().trim()
                    , GEN_LOT_TAPING
                    , CUSTOMER
                    ,"");

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

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

                    if (response.equals("OK")) {
                        if (stopThread == true) {
                            layout_alert.setVisibility(RelativeLayout.GONE);
                            Toast.makeText(TapingLabel_Activity.this, "Print : OK", Toast.LENGTH_SHORT).show();
                            new SweetAlertDialog(TapingLabel_Activity.this, SweetAlertDialog.SUCCESS_TYPE)
                                    .setTitleText("SUCCESS")
                                    .setContentText("Print : OK")
                                    .show();
                            txt_user.setText("");
                            Clear_Layout();
                        }

                    } else {
                        error_print = true;
                        layout_alert.setVisibility(RelativeLayout.GONE);
                        Unblock_button();
                        new SweetAlertDialog(TapingLabel_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_Balance(String rank_card, String rank_card_lot, int qty) {
        try {
            txt_message.setText("Please wait, searching data...");
            layout_alert.setVisibility(View.VISIBLE);

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

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

                    try {
                        JSONArray jArray = new JSONArray(response);

                        if (jArray.length() == 0){ // no history rank card
                            QTY_RANK_CARD = qty;
                            new_rank_card = true; // New RankCard

                        }else {
                            new_rank_card = false;// Old RankCard

                            String  balance = "";
                            for (int i = 0; i < jArray.length(); i++) {
                                balance = jArray.getJSONObject(i).getString("balance").trim();
                            }
                            QTY_RANK_CARD = Integer.parseInt(balance);
                        }
                        if (QTY_RANK_CARD == 0){
//                            new SweetAlertDialog(TapingLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
//                                    .setTitleText("WARNING")
//                                    .setContentText("This Rank Card qty = 0")
//                                    .show();
                            MyAlert alert =  new MyAlert(TapingLabel_Activity.this);
                            alert.setMessage("จำนวน Rank Card = 0");
                            alert.show();
                            if (map_rank_card.size() == 0){
                                Clear_RankCard();
                            }else {
                                txt_lot_no.setText("");
                            }
                        }else{
                            Calculate_Qty();
                        }

                        layout_alert.setVisibility(View.GONE);
                        Log.d(getString(R.string.tag), "QTY_RANK_CARD: " + String.valueOf(QTY_RANK_CARD));
                    }catch (JSONException e) {
                        layout_alert.setVisibility(View.GONE);
                        new SweetAlertDialog(TapingLabel_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();

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

    private void Calculate_Qty() {

        BALANCE_RANK_CARD = 0;
        String sum = txt_sum_qty.getText().toString().trim();
        int sum_qty = Integer.parseInt(sum);
        SUM_QTY = (REQUEST_REEL_QTY - sum_qty);
        Log.d(getString(R.string.tag), "QTY_TAPING: " +
                String.valueOf(SUM_QTY+"="+REQUEST_REEL_QTY+"-"+  sum_qty));

        if (SUM_QTY == 0){
            new SweetAlertDialog(TapingLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("แจ้งเตือน")
                    .setContentText("จำนวนครบแล้ว")
                    .show();
        }else {
            if (QTY_RANK_CARD > SUM_QTY) {
                BALANCE_RANK_CARD = (QTY_RANK_CARD - SUM_QTY);
                Log.d(getString(R.string.tag), "BALANCE_RANK_CARD: " +
                        String.valueOf(BALANCE_RANK_CARD + "=" + QTY_RANK_CARD + "-" + SUM_QTY));

                QTY_REEL_USED = SUM_QTY;
                Log.d(getString(R.string.tag), "QTY_REEL_USE: " + QTY_REEL_USED);
                AddMap_RankCard();

            } else if (QTY_RANK_CARD == SUM_QTY) {
                BALANCE_RANK_CARD = 0;
                QTY_REEL_USED = SUM_QTY;
                Log.d(getString(R.string.tag), "QTY_REEL_USE: " + QTY_REEL_USED);
                AddMap_RankCard();

            } else {//QTY_RANK_CARD < int_QTY_REEL
                if (new_rank_card == true){//rank cardใหม่ ไม่เคยออก taping
                    BALANCE_RANK_CARD = 0;
                    QTY_REEL_USED = QTY_RANK_CARD;
                    Log.d(getString(R.string.tag), "QTY_REEL_USE: " + QTY_REEL_USED);
                    AddMap_RankCard();

                }else {//rank card ที่จำนวนเหลือไม่พอ taping
                    MyAlert alert =  new MyAlert(TapingLabel_Activity.this);
                    alert.setMessage("มีจำนวนไม่พอ Taping"+"\n"+"กรุณาพิมพ์ใบเศษ");

                    if (map_rank_card.size() == 0) {//
                        alert.next_activity(true);
                    }

                    alert.show();
                }
            }
        }
    }

    private void AddMap_RankCard() {
        map_rank_card.put(RANK_CARD+RANK_CARD_LOT, new RankCard_Lists(
                RANK_CARD,
                RANK_CARD_LOT,
                String.valueOf(QTY_REEL_USED) ,
                String.valueOf(QTY_RANK_CARD),
                String.valueOf(BALANCE_RANK_CARD)));
        Log.d(getString(R.string.tag), "AddMap_RankCard: " + map_rank_card.size());

        Set_View_RankCard();
    }

    private void Set_View_RankCard() {
//        txt_lot_no.setText("");
        list_rank_card.clear();

        if (map_rank_card.size() == 0){
            Clear_RankCard();

        }else {
            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, TapingLabel_Activity.this);
        view_rank_card.setAdapter(rankCard_adapter);
    }

    private void Clear_RankCard() {
        txt_model_name.setText("");
        txt_rank.setText("");
        txt_lot_no.setText("");
        txt_sum_qty.setText("0");
        txt_reel_qty.setText("0");
        ics_code = "";
        rank = "";
        ICS_CODE1 = "";
        RANK1 = "";
        scan_rank_card = false;
        if (map_rank_card.size() == 0){
            txt_model_name.setTextColor(Color.parseColor("#FF000000"));
            txt_rank.setTextColor(Color.parseColor("#FF000000"));
        }
    }

    private void Clear_Layout() {
//        txt_user.setText("");
        txt_machine.setText("");
        txt_model_name.setText("");
        txt_rank.setText("");
        txt_lot_no.setText("");
        txt_sum_qty.setText("0");
        txt_reel_qty.setText("0");
        edt_label_qty.setText("2");
        ics_code = "";
        rank = "";
        ICS_CODE1 = "";
        RANK1 = "";
        GEN_LOT_TAPING = "";
        scan_rank_card = false;
        scan_machine = false;
        b_print = false;
        error_print = false;
        stopThread = true;
        map_rank_card.clear();
        txt_model_name.setTextColor(Color.parseColor("#FF000000"));
        txt_rank.setTextColor(Color.parseColor("#FF000000"));
        Unblock_button();
        Set_View_RankCard();
    }



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

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

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

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

//                            if(mc_product_type.trim().equals(item_product_type)){
                            if (map_machine.containsKey(item_product_type)){
                                    Machine_Lists mc = map_machine.get(item_product_type);
                                    machine_no = mc.getMachine_No();
                                    mc_product_type = mc.getType();
                                    delay_time = mc.getDelay_min();
                                    printer_ip = mc.getPrinter_IP();
                                    ready_dt = mc.getReady_dt();
                                    Check_MC_Ready(ready_dt, mc.getMachine_Code());

                                layout_alert.setVisibility(View.GONE);
                            }else{
                                MyAlert alert =  new MyAlert(TapingLabel_Activity.this);
                                alert.setMessage("Type ไม่ตรงกัน!");
                                alert.show();
                                layout_alert.setVisibility(View.GONE);
                            }
                        }
                    }catch (JSONException e) {
                        layout_alert.setVisibility(View.GONE);
                        new SweetAlertDialog(TapingLabel_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();

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

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

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

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

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

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

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

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

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

                    try {
                        JSONArray jArray = new JSONArray(response);
                        if (jArray.length() == 0){
                            layout_alert.setVisibility(View.GONE);
                            txt_machine.setText("");
                            new SweetAlertDialog(TapingLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("แจ้งเตือน")
                                    .setContentText("ไม่พบเครื่องจักร!")
                                    .show();
                        }else {
                            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);
                                }
                                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()));
                            }

                            Log.d(getString(R.string.tag), "ready_dt: " + ready_dt);
                            Log.d(getString(R.string.tag), "map_machine: " + map_machine.size());


                            if (map_rank_card.size() > 0){//scan change machine
                                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();
                                    delay_time = mc.getDelay_min();
                                    printer_ip = mc.getPrinter_IP();
                                    ready_dt = mc.getReady_dt();
                                    Check_MC_Ready(ready_dt, mc.getMachine_Code());

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

                            }else {
                                txt_machine.setText(machine_code);
                                layout_alert.setVisibility(View.GONE);
                            }


//                            if (map_rank_card.size() == 0){
//                                Log.d(getString(R.string.tag), "if map_rank_card.size() == 0: " + ready_dt);
//                                Check_MC_Ready(machine_code);
//                            }else{
//                                Log.d(getString(R.string.tag), "else > 0: " + ready_dt);
////                                if (mc_product_type == item_product_type){
//                                if (map_machine.containsKey(item_product_type)){
//                                    Machine_Lists mc = map_machine.get(item_product_type);
//                                    machine_no = mc.getMachine_No();
//                                    mc_product_type = mc.getType();
//                                    delay_time = mc.getDelay_min();
//                                    printer_ip = mc.getPrinter_IP();
//
//                                    Check_MC_Ready(machine_code);
//
//                                }else{
//                                    layout_alert.setVisibility(View.GONE);
//                                    MyAlert alert =  new MyAlert(TapingLabel_Activity.this);
//                                    alert.setMessage("Type ไม่ตรงกัน!");
//                                    alert.show();
//                                }
//                            }
                        }
                    }catch (JSONException e) {
                        layout_alert.setVisibility(View.GONE);
                        new SweetAlertDialog(TapingLabel_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();

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

    private void Check_MC_Ready(String mc_ready_dt, String machine_code) {
        Log.d(getString(R.string.tag), "ready_dt: " + mc_ready_dt);

        if(!mc_ready_dt.trim().equals("")) {
            Calendar c_ready_dt= ConvertStringToCalendar.convert(mc_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);
                scan_machine = true;

                txt_model_name.setText(NAME);
                txt_rank.setText(rank);
                txt_reel_qty.setText(QTY_REEL);
                REQUEST_REEL_QTY = Integer.parseInt(QTY_REEL);
                scan_rank_card = true;

                if (map_rank_card.size() == 0){//Default data
                    ICS_CODE1 = ics_code;
                    RANK1 = rank;
                }

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

            txt_model_name.setText(NAME);
            txt_rank.setText(rank);
            txt_reel_qty.setText(QTY_REEL);
            REQUEST_REEL_QTY = Integer.parseInt(QTY_REEL);
            scan_rank_card = true;

            if (map_rank_card.size() == 0){//Default data
                ICS_CODE1 = ics_code;
                RANK1 = rank;
            }

        }
        Log.d(getString(R.string.tag), "response: " + machine_no+" | "+ mc_product_type+" | "+delay_time);
        layout_alert.setVisibility(View.GONE);
    }

    @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) {
                        map_rank_card.clear();
                        Set_View_RankCard();
                        Clear_Layout();
                    }
                    break;
            }
        }

        return super.onKeyUp(keyCode, event);
    }

}