package com.tomas.lps_asi;

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

import androidx.constraintlayout.widget.ConstraintLayout;

import com.keyence.autoid.sdk.scan.DecodeResult;
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.AsyncTcpClient;
import com.tomas.lps_asi.lib.common.Scanner;
import com.tomas.lps_asi.lib.common.Utils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import cn.pedant.SweetAlert.SweetAlertDialog;

public class ExpiredLabel_Activity extends Scanner implements View.OnClickListener {
    TextView txt_user, txt_date, txt_machine, txt_lot_no, txt_name, txt_rank, txt_message;
    EditText edt_label_qty;
    Button btn_print;
    boolean  b_print, error_print;
    int LABEL_QTY, PRINT_TIMES;
    String str_date, str_role, old_Taping_lot_no, ICS_Code, Name, Rank, Type, Customer, Machine_no, Taping_qty, GEN_LOT_TAPING,
            dt_taping, Machine_Job_No, dt_to_server, end_dt, start_dt;
    Calendar calendar,end_calendar, start_calendar;
    SimpleDateFormat date_time_fm, date_fm, date_taping_fm;
    ConstraintLayout layout_alert;
    private volatile boolean stopThread = true;

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

        b_print = false;
        stopThread = true;
        error_print = 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_machine = (TextView)findViewById(R.id.txt_machine_code);
        txt_lot_no = (TextView) findViewById(R.id.txt_lot_no);
        txt_name = (TextView) findViewById(R.id.txt_name);
        txt_rank = (TextView) findViewById(R.id.txt_rank);
        txt_message = (TextView)findViewById(R.id.txt_message);

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

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

    }

    @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 (txt_user.getText().toString().trim().equals("")){
            Unblock_button();
            new SweetAlertDialog(ExpiredLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("แจ้งเตือน")
                    .setContentText("กรุณาสแกนรหัสพนักงาน!")
                    .show();
        }else if (txt_lot_no.getText().toString().trim().equals("")){
            Unblock_button();
            new SweetAlertDialog(ExpiredLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("แจ้งเตือน")
                    .setContentText("กรุณาสแกน Taping label!")
                    .show();
        }else {
//            Gen_Lot_Taping();
            Generate_Label();
        }
    }

    private void Clear_Layout() {
        Unblock_button();
        stopThread = true;
        error_print = false;
        txt_machine.setText("");
        txt_lot_no.setText("");
        txt_name.setText("");
        txt_rank.setText("");
        edt_label_qty.setText("3");

    }

    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(ExpiredLabel_Activity.this);
                        alert.setMessage("รหัสพนักงานนี้ไม่ใช่ leader!");
                        alert.show();
                    }
                }else {
                    txt_user.setText("");
                    new SweetAlertDialog(ExpiredLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                            .setTitleText("แจ้งเตือน")
                            .setContentText("ไม่พบรหัสพนักงาน!")
                            .show();
                }
            } else if (data.length() == 16 || data.length() == 19){
                old_Taping_lot_no = data;
                Log.d(getString(R.string.tag), "Taping_lot_no: " + old_Taping_lot_no);
                Check_TapingLot(old_Taping_lot_no);

            } else {
                new SweetAlertDialog(ExpiredLabel_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 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(ExpiredLabel_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("กรุณารอสักครู่ กำลังบันทึกข้อมูล...");

            //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", Taping_qty);
            jsonTapingLabel.put("label_qty", edt_label_qty.getText().toString().trim());
            jsonTapingLabel.put("label_type", Settings.getLabelType());
            jsonTapingLabel.put("remark", "");
            jsonTapingLabel.put("create_dt", dt_to_server);
            jsonTapingLabel.put("create_user_id", txt_user.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",old_Taping_lot_no);
            jsParams.put("ics_code", ICS_Code);
            jsParams.put("product_name", Name);
            jsParams.put("rank", Rank);
            jsParams.put("qty",Taping_qty);
            jsParams.put("qty_used", Taping_qty);
            jsParams.put("balance", Taping_qty);
            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("Ready_dt","");
            json.put("year",year);
            json.put("month",month);
            json.put("date",date);
            json.put("tap_datas",jArray_tapping_lot);
            json.put("label_datas",jArray_tapping_label);
            json.put("rank_card_datas",jArray_RankCard);

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

                        } else {
                            Unblock_button();
                            layout_alert.setVisibility(View.GONE);
                            new SweetAlertDialog(ExpiredLabel_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                    .setTitleText("ERROR")
                                    .setContentText(jsonObject.getString("error"))
                                    .show();
                        }

                    }catch (JSONException e) {
                        Unblock_button();
                        layout_alert.setVisibility(View.GONE);
                        new SweetAlertDialog(ExpiredLabel_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();
        }catch (JSONException e) {
            Unblock_button();
            layout_alert.setVisibility(View.GONE);
            new SweetAlertDialog(ExpiredLabel_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("")
                ||Taping_qty.trim().equals("0")
                ||GEN_LOT_TAPING.trim().equals("")){

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

                    } else {
                        error_print = true;
                        layout_alert.setVisibility(RelativeLayout.GONE);
                        Unblock_button();
                        new SweetAlertDialog(ExpiredLabel_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText("Can't connect to print server")
                                .show();

                    }
                }
            }.execute();
            throw new JSONException(err_msg);
        } catch (JSONException e) {
            Log.e(getString(R.string.tag), "ERROR: " + e.getMessage());

        }
    }


    private void Check_TapingLot(String taping_lot_no) {
        try {
            txt_message.setText("กรุณารอสักครู่ กำลังค้นหาข้อมูล...");
            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);
                            old_Taping_lot_no = "";
                            new SweetAlertDialog(ExpiredLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("แจ้งเตือน")
                                    .setContentText("ไม่พบ Taping Label นี้!")
                                    .show();
                            Clear_Layout();
                        }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();
                            }

                            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(ExpiredLabel_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();

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


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

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

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

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

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

        return super.onKeyUp(keyCode, event);
    }

}