package com.tomas.lps_asi;

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

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

import com.keyence.autoid.sdk.scan.DecodeResult;
import com.tomas.lps_asi.ListData.Machine_Lists;
import com.tomas.lps_asi.ListData.User_Lists;
import com.tomas.lps_asi.lib.KeyMapping;
import com.tomas.lps_asi.lib.MyAlert;
import com.tomas.lps_asi.lib.Settings;
import com.tomas.lps_asi.lib.common.AsyncHttpClient;
import com.tomas.lps_asi.lib.common.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.ParseException;
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, edt_reel_qty;
    Button btn_print;
    Spinner spinner_rank;
    boolean  b_print, error_print;
    Calendar calendar, end_calendar, start_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,  end_dt, start_dt, Product_Type;
    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 scan_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;
        scan_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_id);
        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.setEnabled(false);//can't edit for scan only

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

        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 && scan_taping_label == false) {
                    if (edt_machine.getText().toString().trim().equals("")){
                        edt_ics_code.setText("");
                        new SweetAlertDialog(DefectiveLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                .setTitleText("แจ้งเตือน")
                                .setContentText("กรุณาใส่หมายเลขเครื่องจักร")
                                .show();
                    }else {
                        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 && scan_taping_label == false) {
                    Check_Machine(machine_no);
                }
            }
        });
    }

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

    }

    private void Check_Time() {
        calendar = Calendar.getInstance();
        try {
            Date today = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("hh:mm aa");
            String current_time = sdf.format(today);
            Date start = sdf.parse("08:00 AM");
            Date current = sdf.parse(current_time);

            if (current.before(start)) {
                calendar.add(Calendar.DATE, -1);
            }
            str_date = date_fm.format(calendar.getTime());
            txt_date.setText(str_date);

        } catch (ParseException e) {
            // Invalid date was entered
        }
    }

    @Override
    public void onClick(View 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 (edt_label_qty.getText().toString().equals("")||edt_label_qty.getText().toString().equals("0")){
            edt_label_qty.setText("3");
        }
        if (edt_reel_qty.getText().toString().trim().equals("")||edt_reel_qty.getText().toString().trim().equals("0")){
            Unblock_button();
            new SweetAlertDialog(DefectiveLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("แจ้งเตือน")
                    .setContentText("กรุณาใส่จำนวนให้ถูกต้อง")
                    .show();

        }else 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 {
            if (scan_taping_label == true){
//                Gen_Lot_Taping();
                Generate_Label();
            }else{//manual
                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("");
        edt_reel_qty.setText("");
        list_rank.clear();
        stopThread = true;
        error_print = false;
        scan_taping_label = false;
        edt_machine.setEnabled(true);
        edt_ics_code.setEnabled(true);
        edt_remark.setEnabled(true);
        edt_remark.setEnabled(true);
        edt_reel_qty.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.substring(0, 2).equals("NG")){//scan barcode NG
                String get_data = edt_remark.getText().toString().trim();
                edt_remark.setText(get_data+" "+data);

            } else 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);
                    txt_user.setText(data);

//                    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() == 16 || data.length() == 19){
                edt_old_lot.setText(data);
                Check_TapingLot(data);

            } else {
                new SweetAlertDialog(DefectiveLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                        .setTitleText("แจ้งเตือน")
                        .setContentText("QR Code ไม่ถูกต้อง!")
                        .show();
            }
            Utils.hideKeyboardFrom(getApplicationContext(), default_view);
        } catch (Exception e) {
            Log.e(getString(R.string.tag), "ERROR: " + e.getMessage());
        }
    }

    private void Check_TapingLot(String taping_lot_no) {
        list_rank.clear();
        try {
            txt_message.setText("กรุณารอสักครู่ กำลังค้นหาข้อมูล...");
            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, "ไม่พบ Taping Label นี้!", Toast.LENGTH_SHORT).show();
                            scan_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();
                                QTY_REEL = jArray.getJSONObject(i).getString("taping_qty").trim();
                            }
                            scan_taping_label = true;
                            edt_ics_code.setEnabled(false);
                            edt_machine.setEnabled(false);

                            edt_ics_code.setText(ICS_Code);
                            edt_machine.setText(Machine_no);
                            edt_reel_qty.setText(QTY_REEL);
                            txt_model_name.setText(NAME);
                            mc_product_type = Type;

                            list_rank.add(Rank);
                            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);
                            spinner_rank.setSelection(0);
                            spinner_rank.setEnabled(false);

                            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("กรุณารอสักครู่ กำลังค้นหาข้อมูล...");
            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();
                                Product_Type = jArray.getJSONObject(i).getString("Type").trim();
                                QTY_REEL = jArray.getJSONObject(i).getString("Qty_Reel").trim();

                            }

                            if (map_machine.containsKey(Product_Type)) {
                                edt_reel_qty.setText(QTY_REEL);
                                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()));

                            }else{
                                Clear_Layout();
                                layout_alert.setVisibility(View.GONE);
                                new SweetAlertDialog(DefectiveLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                        .setTitleText("แจ้งเตือน")
                                        .setContentText("Type ไม่ตรงกัน!")
                                        .show();
                            }
                        }
                    }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() {//check item again
        ICS_Code = edt_ics_code.getText().toString().trim();
        Rank = spinner_rank.getSelectedItem().toString().trim();
        try {
            txt_message.setText("กรุณารอสักครู่ กำลังค้นหาข้อมูล...");
            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 และ Rank นี้!")
                                    .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 (map_machine.containsKey(Type)){
//                                Machine_Lists mc = map_machine.get(Type);
//                                Machine_no = mc.getMachine_No();
//                                mc_product_type = mc.getType();
//                                Gen_Lot_Taping();
                            Generate_Label();
//
//                            }else {
//                                layout_alert.setVisibility(View.GONE);
//                                Unblock_button();
//                                Clear_Layout();
//
//                                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 Generate_Label() {
        //get start_dt end_dt
        start_calendar = Calendar.getInstance();
        end_calendar = Calendar.getInstance();
        //date gen lot
        calendar = Calendar.getInstance();
        calendar = (Calendar) calendar.clone();
        try {//check date time before 8:00AM
            Date today = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("hh:mm aa");
            String current_time = sdf.format(today);
            Date start = sdf.parse("08:00 AM");
            Date current = sdf.parse(current_time);

            if (current.before(start)) {
                Log.d("get_start_dt", "before" );

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

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

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

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

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

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

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

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

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

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


        try {
            layout_alert.setVisibility(View.VISIBLE);
            txt_message.setText("กรุณารอสักครู่ กำลังบันทึกข้อมูล...");
            String remark = edt_remark.getText().toString().trim();
            String encode = URLEncoder.encode(remark,"UTF-8");

            //for insert taping_lot
            JSONArray jArray_tapping_lot = 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","");
            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);
            jArray_tapping_lot.put(jsonObj);

            //insert table TapingLabel

            JSONArray jArray_tapping_label = new JSONArray();
            Map<String, String> jsonTapingLabel = new HashMap<>();
            jsonTapingLabel.put("taping_lot_no", "");
            jsonTapingLabel.put("ics_code", ICS_Code);
            jsonTapingLabel.put("product_name",  NAME);
            jsonTapingLabel.put("rank",  Rank);
            jsonTapingLabel.put("type",  Type);
            jsonTapingLabel.put("cust_ref", CUSTOMER);
            jsonTapingLabel.put("machine_no", Machine_no);
            jsonTapingLabel.put("taping_qty", edt_reel_qty.getText().toString().trim());
            jsonTapingLabel.put("label_qty", edt_label_qty.getText().toString().trim());
            jsonTapingLabel.put("label_type", Settings.getLabelType());
            jsonTapingLabel.put("remark", encode);
            jsonTapingLabel.put("create_dt", dt_to_server);
            jsonTapingLabel.put("create_user_id", txt_user.getText().toString().trim());
            jsonTapingLabel.put("ref_id", "");
            JSONObject jsonObjTL = new JSONObject(jsonTapingLabel);
            jArray_tapping_label.put(jsonObjTL);

            //insert table RankCard
            JSONArray jArray_RankCard = new JSONArray();
            Map<String, String> jsParams = new HashMap<>();
            jsParams.put("rank_card", Settings.getLabelType());
            jsParams.put("lot_no", edt_old_lot.getText().toString().trim());
            jsParams.put("ics_code", ICS_Code);
            jsParams.put("product_name", NAME);
            jsParams.put("rank", Rank);
            jsParams.put("qty", edt_reel_qty.getText().toString().trim());
            jsParams.put("qty_used", edt_reel_qty.getText().toString().trim());
            jsParams.put("balance", edt_reel_qty.getText().toString().trim());
            jsParams.put("taping_lot_no", "");
            jsParams.put("create_dt", dt_to_server);
            jsParams.put("ref_id", "");
            JSONObject jsObj = new JSONObject(jsParams);
            jArray_RankCard.put(jsObj);


            JSONObject json = new JSONObject();
            json.put("cmd", "generate_label");
            json.put("label_type", Settings.getLabelType());
            json.put("machine_no",Machine_no );
            json.put("rank",Rank );
            json.put("start_dt",start_dt );
            json.put("end_dt",end_dt );
            json.put("year",year);
            json.put("month",month);
            json.put("date",date);
            json.put("Ready_dt","");
            json.put("tap_datas",jArray_tapping_lot);
            json.put("label_datas",jArray_tapping_label);
            json.put("rank_card_datas",jArray_RankCard);

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

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

            MyAlert alert = new MyAlert(DefectiveLabel_Activity.this);
            alert.setMessage("การสั่งพิมพ์เกิดข้อผิดพลาด +\n+ กรุณาทำรายการใหม่");
            alert.show();

            Clear_Layout();

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

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

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

    class ExampleRunnable implements Runnable {

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

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

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

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

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

        String err_msg = "";
        try {
            err_msg = "Server connection failed!\nPlease contact leader.";
            String payload = String.format(
                    "%s|%s|%s|%s|%s|%s"
                    , ICS_Code
                    , NAME
                    , edt_reel_qty.getText().toString().trim()
                    , 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(View.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(View.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("กรุณารอสักครู่ กำลังค้นหาข้อมูล...");
            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("กรุณารอสักครู่ กำลังค้นหาข้อมูล...");
            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();
                            }

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

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

                                        Command_Print();

                                    } else {
                                        layout_alert.setVisibility(View.GONE);
                                        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();
                                    }
                                } catch (JSONException e) {
                                    Unblock_button();
                                    layout_alert.setVisibility(View.GONE);
                                    e.printStackTrace();
                                    Log.d(getString(R.string.tag), "catch:1 ");
                                }
                            }
                        }
                                .execute();
                    }  catch (JSONException e) {
                        Unblock_button();
                        layout_alert.setVisibility(View.GONE);
                        e.printStackTrace();
                        Log.d(getString(R.string.tag), "catch:2 ");
                    }
                }
                break;
        }
    }

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