package com.tomas.lps_asi;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.content.FileProvider;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
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.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.keyence.autoid.sdk.scan.DecodeResult;
import com.tomas.lps_asi.ListData.RankCard_Lists;
import com.tomas.lps_asi.ListData.User_Lists;
import com.tomas.lps_asi.lib.KeyMapping;
import com.tomas.lps_asi.lib.Model_Name;
import com.tomas.lps_asi.lib.MyAlert;
import com.tomas.lps_asi.lib.Settings;
import com.tomas.lps_asi.lib.SpinAdapterModel;
import com.tomas.lps_asi.lib.SpinObjectModel;
import com.tomas.lps_asi.lib.common.AsyncHttpClient;
import com.tomas.lps_asi.lib.common.AsyncHttpClientMultipart;
import com.tomas.lps_asi.lib.common.AsyncTcpClient;
import com.tomas.lps_asi.lib.common.MyAlertDialog;
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.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
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 ChangeModel_Activity extends Scanner implements View.OnClickListener {
    ConstraintLayout layout_alert;
    TextView txt_date, txt_user, txt_machine, txt_lot_no, txt_message;
    EditText edt_label_qty;
    Spinner spinner_model;
    Calendar calendar, end_calendar, start_calendar;
    String str_date, old_Taping_lot_no, str_role, old_Machine_no, old_Rank, old_Model_name, old_Ics_Code, old_Type, old_Customer, old_Taping_qty, Sub_name,
            GEN_LOT_TAPING, dt_taping, Machine_Job_No, dt_to_server,end_dt, start_dt;
    Button btn_print;
    SimpleDateFormat date_time_fm, date_fm, date_taping_fm;
    boolean  b_print, error_print;
    HashMap<String, Model_Name> HM_ModelName;
    SpinAdapterModel spinAdapterModel;
    List<Model_Name> list_model_names;

    int LABEL_QTY, PRINT_TIMES;
    private volatile boolean stopThread = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_change_model_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());

        HM_ModelName = new LinkedHashMap<String, Model_Name>();
        list_model_names = new ArrayList<Model_Name>();

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

        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_lot_no = (TextView) findViewById(R.id.txt_lot_no);
        spinner_model = (Spinner) findViewById(R.id.spinner_model);
        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);

    }

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

            case R.id.btn_clear:
                if (error_print == false) {
                    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() {
        if (txt_user.getText().toString().equals("")){
            Unblock_button();
            new SweetAlertDialog(ChangeModel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("แจ้งเตือน")
                    .setContentText("กรุณาสแกนรหัสพนักงาน!")
                    .show();
        }else if (txt_lot_no.getText().toString().equals("")) {
            Unblock_button();
            new SweetAlertDialog(ChangeModel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("แจ้งเตือน")
                    .setContentText("กรุณาสแกน Taping label!")
                    .show();
        }else {
            //select and add new model
            Settings.setNewModel((Model_Name) spinAdapterModel.getItem(spinner_model.getSelectedItemPosition()));
//                    dispatchTakePictureIntent();
            Gen_Lot_Taping();
        }
    }

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

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


    private void Clear_Layout() {
        Unblock_button();
        stopThread = true;
        error_print = false;
        txt_machine.setText("");
        txt_lot_no.setText("");
        edt_label_qty.setText("3");
        list_model_names.clear();
        spinAdapterModel = new SpinAdapterModel(
                getApplicationContext(), R.layout.spinner_model, list_model_names.toArray(new Model_Name[list_model_names.size()]));
        spinner_model.setAdapter(spinAdapterModel);
    }

    @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 (data.length() == 6){
                Log.d(getString(R.string.tag), "user : " + data);
//                Check_User(data);
                if (Settings.getMap_user().containsKey(data)){
                    User_Lists lists =  Settings.getMap_user().get(data);
                    str_role = lists.getRole();
                    Log.d(getString(R.string.tag), "role user : " + str_role);

                    if (str_role.trim().equals("LEADER")){
                        txt_user.setText(data);
                    }else {
                        txt_user.setText("");
                        MyAlert alert =  new MyAlert(ChangeModel_Activity.this);
                        alert.setMessage("รหัสพนักงานนี้ไม่ใช่ leader!");
                        alert.show();
                    }

                }else {
                    txt_user.setText("");
                    new SweetAlertDialog(ChangeModel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                            .setTitleText("แจ้งเตือน")
                            .setContentText("ไม่พบรหัสพนักงาน!")
                            .show();
                }
            }else if (data.length() == 16 || data.length() == 19){
                old_Taping_lot_no = data;
                Log.d(getString(R.string.tag), "Taping_lot_no: " + old_Taping_lot_no);
                Check_TapingLot(old_Taping_lot_no);

            }else {
                new SweetAlertDialog(ChangeModel_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 Gen_Lot_Taping() {
//        GEN_LOT_TAPING = "";
//        calendar = Calendar.getInstance();
//        calendar = (Calendar) calendar.clone();
//        dt_taping = date_taping_fm.format(calendar.getTime());
//        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, searching data...");
//
//            JSONObject json = new JSONObject();
//            json.put("cmd", "get_job");
//            json.put("machine_no", old_Machine_no);
//            json.put("type",old_Type);
//            json.put("date", dt_taping);
//
//
//            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 + old_Machine_no + old_Rank;
//                        Log.d(getString(R.string.tag), "GEN_LOT_TAPING: " + GEN_LOT_TAPING);
//
//                        Insert_TapingLot();
//
//
//                    }catch (JSONException e) {
//                        Unblock_button();
//                        layout_alert.setVisibility(View.GONE);
//                        new SweetAlertDialog(ChangeModel_Activity.this, SweetAlertDialog.ERROR_TYPE)
//                                .setTitleText("ERROR")
//                                .setContentText(e.getMessage())
//                                .show();
//                    }
//                }
//            }.execute();
//        }catch (JSONException e) {
//            Unblock_button();
//            layout_alert.setVisibility(View.GONE);
//            new SweetAlertDialog(ChangeModel_Activity.this, SweetAlertDialog.ERROR_TYPE)
//                    .setTitleText("ERROR")
//                    .setContentText(e.getMessage())
//                    .show();
//        }
//    }

    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(ChangeModel_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", old_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 + old_Machine_no + old_Rank;
                        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(ChangeModel_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();
        }catch (JSONException e) {
            Unblock_button();
            layout_alert.setVisibility(View.GONE);
            new SweetAlertDialog(ChangeModel_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", "TP"+old_Machine_no);
            jsonParams.put("machine_no", old_Machine_no);
            jsonParams.put("taping_lot",GEN_LOT_TAPING);
            jsonParams.put("type", old_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_NewTapingLabel();

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

    private void Insert_NewTapingLabel() {//new model
        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", Settings.getNewModel().getICS_Code());
            jsonParams.put("product_name",  Settings.getNewModel().getName());
            jsonParams.put("rank", Settings.getNewModel().getRank());
            jsonParams.put("type",  Settings.getNewModel().getType());
            jsonParams.put("cust_ref", Settings.getNewModel().getCustomer());
            jsonParams.put("machine_no", old_Machine_no);
            jsonParams.put("taping_qty", old_Taping_qty);
            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();//old label insert in to table rank card

                        } else {
                            Unblock_button();
                            layout_alert.setVisibility(View.GONE);
                            new SweetAlertDialog(ChangeModel_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(ChangeModel_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();
        } catch (Exception e) {
            Unblock_button();
            layout_alert.setVisibility(View.GONE);
            new SweetAlertDialog(ChangeModel_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();

                Map<String, String> jsonParams = new HashMap<>();
//                jsonParams.put("rank_card", old_Taping_lot_no);
                jsonParams.put("rank_card", Settings.getLabelType());
                jsonParams.put("lot_no",old_Taping_lot_no);
                jsonParams.put("ics_code", old_Ics_Code);
                jsonParams.put("product_name", old_Model_name);
                jsonParams.put("rank", old_Rank);
                jsonParams.put("qty",old_Taping_qty);
                jsonParams.put("qty_used", old_Taping_qty);
                jsonParams.put("balance", old_Taping_qty);
                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) {

                            Command_Print();

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

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

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

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

    class ExampleRunnable implements Runnable {

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

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

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

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

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

        String err_msg = "";
        try {
            err_msg = "Server connection failed!\nPlease contact leader.";
            String payload = String.format(
                    "%s|%s|%s|%s|%s"
                    , Settings.getNewModel().getICS_Code()
                    , Settings.getNewModel().getName()
                    , Settings.getNewModel().getQty_Reel()
                    , GEN_LOT_TAPING
                    , Settings.getNewModel().getCustomer());

            String tmp = String.format(
                    "%s %s\r\n%s%s"
                    , "PST"
                    ,"192.168.1.2-CHANGE-LABEL"
                    , ""
                    , payload
            );

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

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

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

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

            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 {
                        JSONArray jArray = new JSONArray(response);
                        if (jArray.length() == 0){
                            old_Taping_lot_no = "";
                            layout_alert.setVisibility(View.GONE);
                            new SweetAlertDialog(ChangeModel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("แจ้งเตือน")
                                    .setContentText("ไม่พบ Label!")
                                    .show();
                            Clear_Layout();
                        }else {
                            for (int i = 0; i < jArray.length(); i++) {
                                old_Ics_Code = jArray.getJSONObject(i).getString("ics_code").trim();
                                old_Model_name = jArray.getJSONObject(i).getString("product_name").trim();
                                old_Rank = jArray.getJSONObject(i).getString("rank").trim();
                                old_Type = jArray.getJSONObject(i).getString("type").trim();
                                old_Customer = jArray.getJSONObject(i).getString("cust_ref").trim();
                                old_Machine_no = jArray.getJSONObject(i).getString("machine_no").trim();
                                old_Taping_qty = jArray.getJSONObject(i).getString("taping_qty").trim();
                            }

                            txt_lot_no.setText(taping_lot_no);
                            txt_machine.setText(old_Machine_no);

                            String[] tokens = old_Model_name.split("-",-1);
                            Log.d(getString(R.string.tag), Arrays.deepToString(tokens));

                            Sub_name = tokens[0];
                            Log.d(getString(R.string.tag), old_Model_name+"|"+Sub_name);
                            Query_new_model(Sub_name, old_Rank);
                        }
                    }catch (JSONException e) {
                        layout_alert.setVisibility(View.GONE);
                        new SweetAlertDialog(ChangeModel_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();

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


    private void Query_new_model(String name, String rank) {
        list_model_names.clear();
        try {
            txt_message.setText("Please wait, searching data...");
            layout_alert.setVisibility(View.VISIBLE);

            JSONObject json = new JSONObject();
            json.put("cmd", "new_model");
            json.put("name", name);
            json.put("rank", rank);
            json.put("ics_code", old_Ics_Code);

            new AsyncHttpClient(getApplicationContext(),
                    Settings.getMgmtList().get("web_api")+ "/item_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);
                            new SweetAlertDialog(ChangeModel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("แจ้งเตือน")
                                    .setContentText("ไม่มีรุ่นที่สามารถเปลี่ยนได้!")
                                    .show();
                            Clear_Layout();
                        }else {
                            for (int i = 0; i < jArray.length(); i++) {
                                String ICS_Code = jArray.getJSONObject(i).getString("ICS_Code").trim();
                                String Product_Name = jArray.getJSONObject(i).getString("Product_Name").trim();
                                String Rank = jArray.getJSONObject(i).getString("Rank").trim();
                                String Cust_Ref = jArray.getJSONObject(i).getString("Customer_Reference").trim()== "null" ? "" : jArray.getJSONObject(i).getString("Customer_Reference").trim();;
                                String Qty_Reel = jArray.getJSONObject(i).getString("Qty_Reel").trim();
                                String Type = jArray.getJSONObject(i).getString("Type").trim();

                                HM_ModelName.put(ICS_Code, new Model_Name(ICS_Code, Product_Name, Rank, Cust_Ref, Qty_Reel, Type));
                            }

                            list_model_names = new ArrayList<>();
                            for (String key : HM_ModelName.keySet()) {
                                list_model_names.add(HM_ModelName.get(key));
                            }
                            Log.d(getString(R.string.tag), "HM_ModelName: " + HM_ModelName.size());

                            spinAdapterModel = new SpinAdapterModel(
                                    getApplicationContext(), R.layout.spinner_model, list_model_names.toArray(new Model_Name[list_model_names.size()]));
                            spinner_model.setAdapter(spinAdapterModel);
                            layout_alert.setVisibility(View.GONE);
                        }
                    }catch (JSONException e) {
                        layout_alert.setVisibility(View.GONE);
                        new SweetAlertDialog(ChangeModel_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();

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

    private void Check_User(String user_id) {
        Log.d(getString(R.string.tag), "Check_User: " + user_id);

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

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

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

                    try {
                        JSONArray jArray = new JSONArray(response);
                        if (jArray.length() == 0){
                            layout_alert.setVisibility(View.GONE);
                            txt_user.setText("");
                            new SweetAlertDialog(ChangeModel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("แจ้งเตือน")
                                    .setContentText("ไม่พบรหัสพนักงาน!")
                                    .show();
                        }else {
                            for (int i = 0; i < jArray.length(); i++) {
                                str_role = jArray.getJSONObject(i).getString("Role").trim();
                            }
                            if (str_role.trim().equals("LEADER")){
                                txt_user.setText(user_id);
                                layout_alert.setVisibility(View.GONE);
                            }else {
                                layout_alert.setVisibility(View.GONE);
                                txt_user.setText("");
//                                new SweetAlertDialog(ChangeModel_Activity.this, SweetAlertDialog.WARNING_TYPE)
//                                        .setTitleText("WARNING")
//                                        .setContentText("This user isn't leader!")
//                                        .show();
                                MyAlert alert =  new MyAlert(ChangeModel_Activity.this);
                                alert.setMessage("รหัสพนักงานนี้ไม่ใช่ leader!");
                                alert.show();
                                layout_alert.setVisibility(View.GONE);
                            }
                        }
                    }catch (JSONException e) {
                        layout_alert.setVisibility(View.GONE);
                        new SweetAlertDialog(ChangeModel_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();

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



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

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode >= KeyMapping.P1.getId()
                && keyCode <= KeyMapping.P4.getId())
        {
            switch (KeyMapping.fromId(keyCode)) {
                case P1:
                    finish();
                    break;

                case P2:
                    if (b_print == false){
                        if (error_print == true){//print error --> print again
                            Command_Print();

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

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

                    break;
            }
        }

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