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.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.MediaController;
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.Machine_Lists;
import com.tomas.lps_asi.ListData.RankCard_Lists;
import com.tomas.lps_asi.ListData.User_Lists;
import com.tomas.lps_asi.lib.KeyMapping;
import com.tomas.lps_asi.lib.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.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.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
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 DefectiveLabel_Activity extends Scanner implements View.OnClickListener {
    private static final int REQUEST_IMAGE_CAPTURE = 200;
    public static final int SIGN_INVOICE_ACTIVITY = 100;
    public static final int SIGN_DO_ACTIVITY = 101;
    TextView txt_date, txt_user, txt_model_name, txt_message;
    EditText edt_machine, edt_ics_code, edt_remark, edt_label_qty ,edt_old_lot;
    Button btn_print;
    Spinner spinner_rank;
    boolean  b_print, error_print;
    Calendar calendar;
    Map<String, Machine_Lists>map_machine;
    String str_date, str_role, Model_name, GEN_LOT_TAPING, dt_taping, NAME, CUSTOMER, QTY_REEL, Type, Machine_Job_No, Machine_no,
            Rank, ICS_Code, dt_to_server, mc_product_type, dt_to_photo;
    SimpleDateFormat date_time_fm, date_fm, date_taping_fm, fm_dt_photo;
    ConstraintLayout layout_alert;
    List<String>list_rank;
    int LABEL_QTY, PRINT_TIMES;
    private volatile boolean stopThread = true;
    boolean Taping_label = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_defective_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");
        fm_dt_photo = new SimpleDateFormat("yyyyMMdd_HHmmss");
        str_date = date_fm.format(calendar.getTime());

        list_rank = new ArrayList<String>();
        map_machine = new LinkedHashMap<>();

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

        layout_alert = (ConstraintLayout)findViewById(R.id.layout_alert);
        txt_date = (TextView) findViewById(R.id.txt_date);
        txt_date.setText(str_date);
        txt_user = (TextView) findViewById(R.id.txt_user);
        txt_model_name = (TextView) findViewById(R.id.txt_name);
        txt_message = (TextView)findViewById(R.id.txt_message);

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

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

        edt_old_lot = (EditText)findViewById(R.id.edt_old_lot);
//        edt_old_lot.addTextChangedListener(new TextWatcher(){
//
//            @Override
//            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
//
//            @Override
//            public void onTextChanged(CharSequence s, int start, int before, int count) { }
//
//            @Override
//            public void afterTextChanged(Editable textVal) {
//                String old_lot_no = textVal.toString();
//                if (old_lot_no.length() == 16 || old_lot_no.length() == 19 ) {
//                    Check_TapingLot(old_lot_no);
//                }
//            }
//        });

        edt_ics_code = (EditText) findViewById(R.id.edt_ics_code);
        edt_ics_code.requestFocus();
        edt_ics_code.setShowSoftInputOnFocus(false);
        edt_ics_code.addTextChangedListener(new TextWatcher(){

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) { }

            @Override
            public void afterTextChanged(Editable textVal) {
                String ics_code = textVal.toString();
                if (ics_code.length() == 10) {
                    Query_Rank(ics_code);
                }
            }
        });

        edt_machine = (EditText) findViewById(R.id.edt_machine);
        edt_machine.addTextChangedListener(new TextWatcher(){

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) { }

            @Override
            public void afterTextChanged(Editable textVal) {
                String machine_no = textVal.toString();
                if (machine_no.length() == 2) {
                    Check_Machine(machine_no);
                }
            }
        });
    }


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

        }
    }

    private void Check_DataInput() {
        if (txt_user.getText().toString().trim().equals("")) {
            Unblock_button();
            new SweetAlertDialog(DefectiveLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("แจ้งเตือน")
                    .setContentText("กรุณาสแกนรหัสพนักงาน")
                    .show();

        } else if (edt_machine.getText().toString().trim().equals("")) {
            Unblock_button();
            new SweetAlertDialog(DefectiveLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("แจ้งเตือน")
                    .setContentText("กรุณากรอกหมายเลขเครื่องจักร.!")
                    .show();

        } else if (edt_ics_code.getText().toString().equals("")) {
            Unblock_button();
            new SweetAlertDialog(DefectiveLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("แจ้งเตือน")
                    .setContentText("กรุณากรอก ICS Code!")
                    .show();

        } else if (edt_remark.getText().toString().trim().equals("")) {
            Unblock_button();
            new SweetAlertDialog(DefectiveLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("แจ้งเตือน")
                    .setContentText("กรุณากรอก Remark!")
                    .show();

        } else {
            Check_Item();
        }
    }

    private void Clear_Layout() {
        Unblock_button();
        edt_machine.setText("");
        edt_ics_code.setText("");
        edt_old_lot.setText("");
        txt_model_name.setText("");
        edt_label_qty.setText("3");
        edt_remark.setText("");
        list_rank.clear();
        stopThread = true;
        error_print = false;
        edt_machine.setEnabled(true);
        edt_ics_code.setEnabled(true);
        edt_remark.setEnabled(true);
        spinner_rank.setEnabled(true);
        ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>
                (getApplicationContext(), R.layout.spinner_model, list_rank);
        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner_rank.setAdapter(dataAdapter);
    }

    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);
    }
    @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(DefectiveLabel_Activity.this);
                        alert.setMessage("รหัสพนักงานนี้ไม่ใช่ leader!");
                        alert.show();
                    }
                }else {
                    txt_user.setText("");
                    new SweetAlertDialog(DefectiveLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                            .setTitleText("แจ้งเตือน")
                            .setContentText("ไม่พบรหัสพนักงาน!")
                            .show();
                }
            } else if(data.length() == 10){
                edt_ics_code.setText(data);

            } else if (data.length() == 16 || data.length() == 19){
                edt_old_lot.setText(data);

            } else {
                String get_data = edt_remark.getText().toString().trim();
                edt_remark.setText(get_data+" "+data);
//                new SweetAlertDialog(DefectiveLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
//                        .setTitleText("WARNING")
//                        .setContentText("Invalid QR code!")
//                        .show();
            }
            Utils.hideKeyboardFrom(getApplicationContext(), default_view);
        } catch (Exception 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){
//                            layout_alert.setVisibility(View.GONE);
//                            Toast.makeText(DefectiveLabel_Activity.this, "ไม่พบ Label!", Toast.LENGTH_SHORT).show();
//                            Taping_label = false;
//                        }else {
//                            for (int i = 0; i < jArray.length(); i++) {
//                                ICS_Code = jArray.getJSONObject(i).getString("ics_code").trim();
//                                Name = jArray.getJSONObject(i).getString("product_name").trim();
//                                Rank = jArray.getJSONObject(i).getString("rank").trim();
//                                Type = jArray.getJSONObject(i).getString("type").trim();
//                                Customer = jArray.getJSONObject(i).getString("cust_ref").trim();
//                                Machine_no = jArray.getJSONObject(i).getString("machine_no").trim();
//                                Taping_qty = jArray.getJSONObject(i).getString("taping_qty").trim();
//                            }
//
//                            Taping_label = true;
//                            txt_lot_no.setText(taping_lot_no);
//                            txt_name.setText(Name);
//                            txt_rank.setText(Rank);
//                            txt_machine.setText(Machine_no);
//                            layout_alert.setVisibility(View.GONE);
//                        }
//                    }catch (JSONException e) {
//                        layout_alert.setVisibility(View.GONE);
//                        new SweetAlertDialog(DefectiveLabel_Activity.this, SweetAlertDialog.ERROR_TYPE)
//                                .setTitleText("ERROR")
//                                .setContentText(e.getMessage())
//                                .show();
//                    }
//                }
//            }.execute();
//
//        }catch (JSONException e) {
//            layout_alert.setVisibility(View.GONE);
//            new SweetAlertDialog(DefectiveLabel_Activity.this, SweetAlertDialog.ERROR_TYPE)
//                    .setTitleText("ERROR")
//                    .setContentText(e.getMessage())
//                    .show();
//        }
//    }

    private void Query_Rank(String ics_code) {
        Log.e(getString(R.string.tag), "Search_item: " + ics_code);
        list_rank.clear();
        try {
            txt_message.setText("Please wait, searching data...");
            layout_alert.setVisibility(View.VISIBLE);

            JSONObject json = new JSONObject();
            json.put("cmd", "search_rank");
            json.put("ics_code", 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(DefectiveLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("แจ้งเตือน")
                                    .setContentText("ไม่พบ ICS Code!")
                                    .show();
                            Clear_Layout();
                        }else {

                            for (int i = 0; i < jArray.length(); i++) {
                                list_rank.add(jArray.getJSONObject(i).getString("Rank").trim());
                                Model_name = jArray.getJSONObject(i).getString("Product_Name").trim();

                            }

                            txt_model_name.setText(Model_name);

                            ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>
                                    (getApplicationContext(), R.layout.spinner_model, list_rank);
                            dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                            spinner_rank.setAdapter(dataAdapter);

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

        }catch (JSONException e) {
            layout_alert.setVisibility(View.GONE);
            new SweetAlertDialog(DefectiveLabel_Activity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage())
                    .show();
        }
    }
    private void Check_Item() {
        ICS_Code = edt_ics_code.getText().toString().trim();
        Rank = spinner_rank.getSelectedItem().toString().trim();
        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);
                            Unblock_button();
                            Clear_Layout();
                            new SweetAlertDialog(DefectiveLabel_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();
                                Type = jArray.getJSONObject(i).getString("Type").trim();
                            }
                            Log.e(getString(R.string.tag), "Type: "+Type);
//                            if (mc_product_type.trim().equals(Type)) {
                            if (map_machine.containsKey(Type)){
                                Machine_Lists mc = map_machine.get(Type);
                                Machine_no = mc.getMachine_No();
                                mc_product_type = mc.getType();
                                Gen_Lot_Taping();

                            }else {
                                layout_alert.setVisibility(View.GONE);
                                Unblock_button();
                                Clear_Layout();
//                                new SweetAlertDialog(DefectiveLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
//                                        .setTitleText("Mismatch")
//                                        .setContentText("Machine Type : "+ mc_product_type)
//                                        .show();
                                MyAlert alert =  new MyAlert(DefectiveLabel_Activity.this);
                                alert.setMessage("Type ไม่ตรงกัน!");
                                alert.show();
                                layout_alert.setVisibility(View.GONE);
                            }
                        }
                    }catch (JSONException e) {
                        layout_alert.setVisibility(View.GONE);
                        Unblock_button();
                        Clear_Layout();
                        new SweetAlertDialog(DefectiveLabel_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();

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

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

        Machine_no = edt_machine.getText().toString().trim();

        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", Machine_no);
            json.put("type",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 + Machine_no + Rank;
                        Log.d(getString(R.string.tag), "GEN_LOT_TAPING: " + GEN_LOT_TAPING);

                        dispatchTakePictureIntent();

                    }catch (JSONException e) {
                        Unblock_button();
                        layout_alert.setVisibility(View.GONE);
                        new SweetAlertDialog(DefectiveLabel_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();
        }catch (JSONException e) {
            Unblock_button();
            layout_alert.setVisibility(View.GONE);
            new SweetAlertDialog(DefectiveLabel_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"+Machine_no);
            jsonParams.put("machine_no", Machine_no);
            jsonParams.put("taping_lot",GEN_LOT_TAPING);
            jsonParams.put("type", 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(DefectiveLabel_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(DefectiveLabel_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();
        } catch (Exception e) {
            Unblock_button();
            layout_alert.setVisibility(View.GONE);
            new SweetAlertDialog(DefectiveLabel_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...");

            String remark = edt_remark.getText().toString().trim();
            String encode = URLEncoder.encode(remark,"UTF-8");

            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_Code);
            jsonParams.put("product_name",  NAME);
            jsonParams.put("rank",  Rank);
            jsonParams.put("type",  Type);
            jsonParams.put("cust_ref", CUSTOMER);
            jsonParams.put("machine_no", Machine_no);
            jsonParams.put("taping_qty", QTY_REEL);
            jsonParams.put("label_qty", edt_label_qty.getText().toString().trim());
            jsonParams.put("label_type", Settings.getLabelType());
            jsonParams.put("remark", encode);
            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(DefectiveLabel_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(DefectiveLabel_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();
        } catch (Exception e) {
            Unblock_button();
            layout_alert.setVisibility(View.GONE);
            new SweetAlertDialog(DefectiveLabel_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", Settings.getLabelType());
                jsonParams.put("lot_no", edt_old_lot.getText().toString().trim());
                jsonParams.put("ics_code", ICS_Code);
                jsonParams.put("product_name", NAME);
                jsonParams.put("rank", Rank);
                jsonParams.put("qty", QTY_REEL);
                jsonParams.put("qty_used", QTY_REEL);
                jsonParams.put("balance", QTY_REEL);
                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(DefectiveLabel_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(DefectiveLabel_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();
        } catch (Exception e) {
            Unblock_button();
            layout_alert.setVisibility(View.GONE);
            new SweetAlertDialog(DefectiveLabel_Activity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage())
                    .show();
        }
    }

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

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

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

    class ExampleRunnable implements Runnable {

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

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

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

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

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

        String err_msg = "";
        try {
            err_msg = "Server connection failed!\nPlease contact leader.";
            String payload = String.format(
                    "%s|%s|%s|%s|%s"
                    , ICS_Code
                    , NAME
                    , QTY_REEL
                    , GEN_LOT_TAPING
                    , CUSTOMER);

            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) {
                            txt_user.setText("");
                            Clear_Layout();
                            layout_alert.setVisibility(RelativeLayout.GONE);
                            Toast.makeText(DefectiveLabel_Activity.this, "Print : OK", Toast.LENGTH_SHORT).show();
                            new SweetAlertDialog(DefectiveLabel_Activity.this, SweetAlertDialog.SUCCESS_TYPE)
                                    .setTitleText("SUCCESS")
                                    .setContentText("Print : OK")
                                    .show();
                        }

                    } else {
                        error_print = true;
                        Unblock_button();
                        layout_alert.setVisibility(RelativeLayout.GONE);

                        edt_machine.setEnabled(false);
                        edt_ics_code.setEnabled(false);
                        edt_remark.setEnabled(false);
                        spinner_rank.setEnabled(false);

                        new SweetAlertDialog(DefectiveLabel_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_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(DefectiveLabel_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(DefectiveLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
//                                        .setTitleText("WARNING")
//                                        .setContentText("This user isn't leader!")
//                                        .show();
                                MyAlert alert =  new MyAlert(DefectiveLabel_Activity.this);
                                alert.setMessage("รหัสพนักงานนี้ไม่ใช่ leader!!");
                                alert.show();
                                layout_alert.setVisibility(View.GONE);
                            }
                        }
                    }catch (JSONException e) {
                        layout_alert.setVisibility(View.GONE);
                        new SweetAlertDialog(DefectiveLabel_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();

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

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

            JSONObject json = new JSONObject();
            json.put("cmd", "check_machine_no");
            json.put("machine_no", machine_no);

            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);
                            edt_machine.setText("");
                            new SweetAlertDialog(DefectiveLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("แจ้งเตือน")
                                    .setContentText("ไม่พบเครื่องจักร!")
                                    .show();
                        }else {
                            for (int i = 0; i < jArray.length(); i++) {
                                map_machine.put(jArray.getJSONObject(i).getString("Type").trim(),
                                        new Machine_Lists(
                                                jArray.getJSONObject(i).getString("Machine_No").trim(),
                                                jArray.getJSONObject(i).getString("Machine_Code").trim(),
                                                jArray.getJSONObject(i).getString("Type").trim(),
                                                jArray.getJSONObject(i).getString("Delay_min").trim(),
                                                "",
                                                jArray.getJSONObject(i).getString("Printer_IP").trim()));
                                Machine_no = jArray.getJSONObject(i).getString("Machine_No").trim();
//                                mc_product_type = jArray.getJSONObject(i).getString("Type").trim();
//                                printer_ip = jArray.getJSONObject(i).getString("Printer_IP").trim();
                            }

                            layout_alert.setVisibility(View.GONE);

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

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

    private void dispatchTakePictureIntent() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // Ensure that there's a camera activity to handle the intent
        Boolean ItIsEmu = true;
        if (takePictureIntent.resolveActivity(getPackageManager()) != null
                || ItIsEmu) {
            // Create the File where the photo should go
            File photoFile = null;
            try {
                photoFile = createImageFile();
            } catch (IOException ex) {
                // Error occurred while creating the File
                ex.printStackTrace();
            }
            // Continue only if the File was successfully created
            if (photoFile != null) {
                Uri photoURI = FileProvider.getUriForFile(this,
                        "com.tomas.lps_asi.fileprovider",
                        photoFile);
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
            } else {
                Toast.makeText(getApplicationContext(), "Photo file cannot be created!!", Toast.LENGTH_LONG).show();
            }
        } else {
            Toast.makeText(getApplicationContext(), "Camera activity not found!!", Toast.LENGTH_LONG).show();
        }
        Unblock_button();
    }

    private Bitmap getPic() {

        // Get the dimensions of the bitmap
        BitmapFactory.Options bmOptions = new BitmapFactory.Options();
        bmOptions.inJustDecodeBounds = true;

        BitmapFactory.decodeFile(currentPhotoPath, bmOptions);

        int photoW = bmOptions.outWidth;
        int photoH = bmOptions.outHeight;

        // Determine how much to scale down the image
        //int scaleFactor = Math.max(1, Math.min(photoW/targetW, photoH/targetH));
        int scaleFactor = 1; // not scale

        // Decode the image file into a Bitmap sized to fill the View
        bmOptions.inJustDecodeBounds = false;
        bmOptions.inSampleSize = scaleFactor;
        bmOptions.inPurgeable = true;

        Bitmap bitmap = BitmapFactory.decodeFile(currentPhotoPath, bmOptions);
        return bitmap;
    }

    String currentPhotoPath;
    private File createImageFile() throws IOException {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
        );

        // Save a file: path for use with ACTION_VIEW intents
        currentPhotoPath = image.getAbsolutePath();
        return image;
    }

    @SuppressLint("StaticFieldLeak")
    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case SIGN_INVOICE_ACTIVITY:
            case SIGN_DO_ACTIVITY:

                if (resultCode == Activity.RESULT_OK) {
                    finish();
                }
                break;
            case REQUEST_IMAGE_CAPTURE:
                if (resultCode == Activity.RESULT_OK) {
                    layout_alert.setVisibility(View.VISIBLE);
                    txt_message.setText("Please wait, saving photo...");

                    Bitmap photo = getPic();

                    // Save picture to server
                    calendar = Calendar.getInstance();
                    calendar = (Calendar) calendar.clone();
                    dt_to_photo = fm_dt_photo.format(calendar.getTime());
                    Log.d(getString(R.string.tag), "datetime_to_server: " + dt_to_photo);

                    try {
                        Map<String, Object> params = new HashMap<>();
                        String filename = GEN_LOT_TAPING+"_"+dt_to_photo+".jpeg";
                        Log.d(getString(R.string.tag), "filename: " + filename);

                        String url = Settings.getMgmtList().get("web_api") + "/save_image.php";
                        JSONObject json = new JSONObject();
                        json.put("image_file", filename);
                        params.put("json", json.toString());

                        ByteArrayOutputStream bos = new ByteArrayOutputStream();
                        photo.compress(Bitmap.CompressFormat.JPEG, 100, bos);
                        byte[] bytes = Base64.getEncoder().encode(bos.toByteArray());
                        params.put(filename, bytes);

                        new AsyncHttpClientMultipart(getApplicationContext()
                                ,url
                                , params
                        ) {
                            @Override
                            public void onFinished(String response, int resp_code) {
                                Log.d(getString(R.string.tag), "response: " + response);

                                try {
                                    JSONObject jsonObject = new JSONObject(response);
                                    Log.d(getString(R.string.tag), "response : " + jsonObject.getString("status"));
                                    if (jsonObject.getString("status").equals("success")) {
                                        Toast.makeText(getApplicationContext(), "Photo saved.", Toast.LENGTH_LONG).show();

                                        // Try delete temporary file
                                        File file = new File(currentPhotoPath);
                                        boolean deleted = file.delete();
                                        Log.d(getString(R.string.tag), "file currentPhotoPath: " + currentPhotoPath);
                                        Log.d(getString(R.string.tag), "file deleted: " + deleted);
                                        deleteImage(currentPhotoPath);

                                        Insert_TapingLot();

                                    } else {

                                        MyAlertDialog dialog = new MyAlertDialog(
                                                DefectiveLabel_Activity.this
                                                , "Error"
                                                , "Please report the problems to Tomas Tech."
                                                , new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog, int which) {
                                            }
                                        }
                                        );
                                    }
                                    Unblock_button();
                                    layout_alert.setVisibility(View.GONE);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                    Log.d(getString(R.string.tag), "catch:1 ");
                                }
                            }
                        }
                                .execute();
                    }  catch (JSONException e) {
                        e.printStackTrace();
                        Log.d(getString(R.string.tag), "catch:2 ");
                    }
                }
                break;
        }
        Unblock_button();
    }

    public void deleteImage(String PhotoPath) {
        String file_dj_path = Environment.getExternalStorageDirectory() + PhotoPath;
        File fdelete = new File(file_dj_path);
        if (fdelete.exists()) {
            if (fdelete.delete()) {
                Log.e("-->", "file Deleted :" + file_dj_path);
                callBroadCast();
            } else {
                Log.e("-->", "file not Deleted :" + file_dj_path);
            }
        }
    }

    public void callBroadCast() {
        if (Build.VERSION.SDK_INT >= 14) {
            Log.e("-->", " >= 14");
            MediaScannerConnection.scanFile(this, new String[]{Environment.getExternalStorageDirectory().toString()}, null, new MediaScannerConnection.OnScanCompletedListener() {
                /*
                 *   (non-Javadoc)
                 * @see android.media.MediaScannerConnection.OnScanCompletedListener#onScanCompleted(java.lang.String, android.net.Uri)
                 */
                public void onScanCompleted(String path, Uri uri) {
                    Log.e("ExternalStorage", "Scanned " + path + ":");
                    Log.e("ExternalStorage", "-> uri=" + uri);
                }
            });
        } else {
            Log.e("-->", " < 14");
            sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
                    Uri.parse("file://" + Environment.getExternalStorageDirectory())));
        }
    }

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