package com.tomas.ht_mast;

import androidx.appcompat.app.AppCompatActivity;

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

import com.keyence.autoid.sdk.scan.DecodeResult;
import com.tomas.ht_mast.ListData.Payload_list;
import com.tomas.ht_mast.lib.ActionType;
import com.tomas.ht_mast.lib.AlertProgress;
import com.tomas.ht_mast.lib.KeyMapping;
import com.tomas.ht_mast.lib.Scanner;
import com.tomas.ht_mast.lib.Settings;
import com.tomas.ht_mast.lib.common.AsyncHttpClient;
import com.tomas.ht_mast.lib.common.AsyncTcpClient;
import com.tomas.ht_mast.lib.common.DatetimeUtil;
import com.tomas.ht_mast.lib.common.Utils;

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

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import cn.pedant.SweetAlert.SweetAlertDialog;

public class RePrintLabel_Activity extends Scanner implements View.OnClickListener {
    TextView txt_user, txt_device, txt_part_no, txt_lot_no, txt_box_no;
    EditText edt_id;
    String label_id, str_parts_no, str_lot_no, str_box;
    boolean b_confirm;
    List<Payload_list> payload_list;
    AlertProgress alert;
    int LABEL_QTY, PRINT_TIMES;
    Button btn_confirm;
    private volatile boolean stopThread = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_re_print_label);
        default_view = (EditText) findViewById(R.id.txt_label_issue_tmp);

        b_confirm = false;
        label_id = "";
        str_parts_no = "";
        str_lot_no = "";
        str_box = "";

        stopThread = true;

        payload_list = new ArrayList<Payload_list>();
        alert = new AlertProgress(RePrintLabel_Activity.this);
        txt_user = (TextView) findViewById(R.id.txt_user);
        txt_user.setText("User : "+ Settings.getLoginUser().getName());

        txt_device = (TextView) findViewById(R.id.txt_device);
        txt_device.setText("Device : "+Settings.getDeviceNo());

        txt_part_no = (TextView) findViewById(R.id.txt_part_no);
        txt_lot_no = (TextView) findViewById(R.id.txt_lot_no);
        txt_box_no = (TextView) findViewById(R.id.txt_box_no);

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

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

    }

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

            case R.id.btn_clear:
                Clear_layout();
                break;

            case R.id.btn_confirm:
                if (b_confirm == false) {
                    Block_button();
                    Check_Condition();
                }
                break;
        }

    }

    private void Check_Condition() {
        if (edt_id.getText().toString().trim().equals("")){
            if (txt_part_no.getText().toString().trim().equals("")){
                new SweetAlertDialog(RePrintLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                        .setTitleText("WARNING")
                        .setContentText("Please complete information!")
                        .show();
            }else{
                Label_Detail();
            }

        }else {
            Label_Detail();
        }
    }

    private void Block_button() {
        b_confirm = true;
        btn_confirm.setEnabled(false);
        btn_confirm.setBackgroundResource(R.drawable.button_background_gray);
    }

    private void Unblock_button() {
        b_confirm = false;
        btn_confirm.setEnabled(true);
        btn_confirm.setBackgroundResource(R.drawable.button_background_blue);
    }


    private void Clear_layout() {
        stopThread = true;
        label_id = "";
        str_parts_no = "";
        str_lot_no = "";
        str_box = "";
        b_confirm = false;
        txt_box_no.setText("");
        txt_lot_no.setText("");
        txt_part_no.setText("");
        edt_id.setText("");
        Unblock_button();
    }

    @Override
    public void processData(String data, DecodeResult.Result result, String codeType) {
        if (data.trim().equals(""))
            return;
        try {
            Log.d(getString(R.string.tag), "data scan: " + data);
            String[] tokens = data.split(getString(R.string.DELIMITER_SCAN_TOKEN),-1);
            Log.d(getString(R.string.tag), Arrays.deepToString(tokens));

            if (tokens.length == 7){
                str_parts_no = tokens[1];
                str_lot_no = tokens[3];
                str_box = tokens[6];

                txt_part_no.setText(str_parts_no);
                txt_lot_no.setText(str_lot_no);
                txt_box_no.setText(str_box);

            }else {
                new SweetAlertDialog(RePrintLabel_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 Label_Detail() {
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "LABEL/DETAIL/PAYLOAD");
            json.put("id", edt_id.getText().toString().trim());
            json.put("parts_no", str_parts_no);
            json.put("lot_no", str_lot_no);
            json.put("serial_no", str_box);

            new AsyncHttpClient(getApplicationContext(),
                    Settings.getMgmtList().get("web_api") + "/ht_api.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 value = jsonObject.getString("value");
                        JSONArray jArray = new JSONArray(value);

                        if (jArray.length() == 0){
                            Unblock_button();
                            new SweetAlertDialog(RePrintLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("WARNING")
                                    .setContentText("Not found label!!")
                                    .show();
                            return;
                        }else {
                            LABEL_QTY = jArray.length();
                            payload_list.clear();
                            for (int i = 0; i < jArray.length(); i++){
                                String  scrap_flg =  jArray.getJSONObject(i).getString("scrap_flg").trim();
                                if(scrap_flg.trim().equals("1")){
                                    scrap_flg =  "-SC";
                                }else {
                                    scrap_flg =  "";
                                }

                                payload_list.add(new Payload_list(
                                        jArray.getJSONObject(i).getString("id"),
                                        scrap_flg,
                                        jArray.getJSONObject(i).getString("payload"),
                                       ""));
                            }
                            //check printer
                            if (Settings.getPrinter().trim().equals("")
                                    ||Settings.getPrinter().trim().equals(null)
                                    ||Settings.getPrinter().trim().equals("null")){
                                new SweetAlertDialog(RePrintLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                        .setTitleText("WARNING")
                                        .setContentText("Please setting printer")
                                        .show();
                                Unblock_button();
                            }else {

                                    Command_Print();

                            }
                        }


                    }catch (JSONException e) {
                        Unblock_button();
                        new SweetAlertDialog(RePrintLabel_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();

        }catch (JSONException e) {
            Unblock_button();
            new SweetAlertDialog(RePrintLabel_Activity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage())
                    .show();
        }

    }

    private void Command_Print() {
        alert.setMessage("           Printing label....         ");
        alert.show();

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

                } 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(getString(R.string.tag), "stopThread: " + stopThread);
        }

        Payload_list payload_l = payload_list.get(PRINT_TIMES-1);
        String payload = payload_l.getPayload();
        String scrap_flg = payload_l.getScrap_flg();
        Log.d("payload", payload_l.getId()+"|" + payload);

        String err_msg = "";
        try {
            err_msg = "Server connection failed!\nPlease contact leader.";

            String tmp = String.format(
                    "%s %s%s%s\r\n%s"
                    , "PST"
                    , Settings.getMgmtList().get("printer_preset")
                    , Settings.getPrinter()
                    , scrap_flg
//                    , Settings.getDeviceNo()
                    , payload

            );

            Log.d(getString(R.string.tag), "payload: " + payload);
            new AsyncTcpClient(getApplicationContext(),
                    Settings.getMgmtList().get("printer_server_host"),
                    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) {
                            alert.dismiss();
                            Clear_layout();
                            Toast.makeText(RePrintLabel_Activity.this,"Print success", Toast.LENGTH_SHORT).show();

                        }
                    } else {
                        alert.dismiss();
                        Unblock_button();
                        new SweetAlertDialog(RePrintLabel_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());
        }
    }


    @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 P3:
                    Clear_layout();
                    break;

                case P4:
                    if (b_confirm == false) {
                        Block_button();
                        Check_Condition();
                    }

                    break;

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