package com.tomas.ckd_system;


import static com.tomas.ckd_system.WsProtocol.COMMAND.RESET_REQUEST;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.tomas.ckd_system.lib.ProductionSchedule;
import com.tomas.ckd_system.lib.Settings;
import com.tomas.ckd_system.lib.common.CallbackListener;
import com.tomas.ckd_system.lib.common.MessageListener;

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

import java.util.Arrays;

import cn.pedant.SweetAlert.SweetAlertDialog;
import okhttp3.WebSocket;

public class MeijiCard_Activity extends AppCompatActivity implements View.OnClickListener, MessageListener, CallbackListener {
    TextView txt_HT;
    String str_url_meiji_card, str_job_id, str_schedule_id;
    Intent intent_pdf;
    boolean isOpenPDF;
    int pdf_content = 1001;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_meiji_card);
        // update MessageListener class
        WsClient.getInstance().setOnMessageListener(this);

        txt_HT = (TextView)findViewById(R.id.txt_device_ht);
        txt_HT.setText("Handy terminal #"+Settings.getDeviceHT().getDevice_id());

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_main:
                try {
                    JSONObject j_ext;
                    j_ext = new JSONObject();
                    j_ext.put("device_id", Settings.getDeviceNo());
                    j_ext.put("user_id", Settings.getLoginUser().getId());
                    j_ext.put("device_type", getString(R.string.device_type));
                    j_ext.put("pair_id", Settings.getDeviceHT().getDevice_id());
                    j_ext.put("pair_dev_type",getString(R.string.pair_dev_type));
                    WsClient.getInstance().sendMessage(
                            WsProtocol.encapsulation(
                                    WsProtocol.COMMAND.REGISTER_REQUEST.toString(),
                                    j_ext
                            )
                    );

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

                finish();

                break;
        }
    }

    @Override
    public void onMessage(WebSocket webSocket, String text) {
        Log.d(getString(R.string.tag), String.format("%s : received -> \"%s\"", this.getLocalClassName(),
                text));
        runOnUiThread(new Runnable() {
            @Override
            public void run() {

                try {
                    JSONObject jsonObject = new JSONObject(text);
                    JSONObject j_ext;

                    switch (WsProtocol.COMMAND.valueOf(jsonObject.getString("cmd"))) {
                        case MEIJI_CARD_DISPLAY_REQUEST:
                            Log.d(getString(R.string.tag), "cmd : MEIJI_CARD_DISPLAY_REQUEST");

                            j_ext = new JSONObject(jsonObject.getString("ext"));
                            str_url_meiji_card = j_ext.getString("url_meiji_card");
                            str_job_id = j_ext.getString("job_id");
                            str_schedule_id = j_ext.getString("schedule_id");

                            Log.d(getString(R.string.tag), "url_meiji_card : " + str_url_meiji_card);
                            Log.d(getString(R.string.tag), "job_id : " + str_job_id);
                            Log.d(getString(R.string.tag), "schedule_id : " + str_schedule_id);

                            str_url_meiji_card = str_url_meiji_card.replace("'\'","");
                            String[] tokens = str_url_meiji_card.split("/");
                            if (tokens.length == 5) {
                                str_url_meiji_card = tokens[4].toString();

                                try {
                                    WsClient.getInstance().sendMessage(
                                            WsProtocol.encapsulation(
                                                    WsProtocol.COMMAND.MEIJI_CARD_DISPLAY_ACK.toString(),
                                                    null
                                            )
                                    );

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

                                } catch (Exception e) {
                                    new SweetAlertDialog(MeijiCard_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                            .setTitleText("ERROR")
                                            .setContentText(e.getMessage())
                                            .show();
                                }

                                Log.d(getString(R.string.tag), "path_pdf1 : " + str_url_meiji_card);


                                String url_pdf = Settings.getMgmtList().get("web_api") + "/res/MeijiCard/" + str_url_meiji_card;
                                Log.d(getString(R.string.tag), "path_pdf : " + url_pdf);

                                if (isOpenPDF) {
                                    finishActivity(pdf_content);
                                }

                                intent_pdf = new Intent();
                                intent_pdf.setDataAndType(Uri.parse(url_pdf), "application/pdf");
                                startActivityForResult(intent_pdf, pdf_content);
                                isOpenPDF = true;

                                //send even log
                                j_ext = new JSONObject();
                                j_ext.put("user_id", Settings.getLoginUser().getId());
                                j_ext.put("device_id", Settings.getDeviceNo());
                                j_ext.put("device_type", getString(R.string.device_type));
                                j_ext.put("job_id", str_job_id);
                                j_ext.put("event", WsProtocol.EVENT.TB_MEIJI_CARD_SUCCESS);
                                j_ext.put("status", ProductionSchedule.STATUS.WORKING);
                                j_ext.put("stage", ProductionSchedule.STAGE.RECEIVING);
                                j_ext.put("schedule_id", str_schedule_id);
                                WsClient.getInstance().sendMessage(
                                        WsProtocol.encapsulation(
                                                WsProtocol.COMMAND.EVENT_LOG_REQUEST.toString(),
                                                j_ext
                                        )
                                );
                            }else {
                                new SweetAlertDialog(MeijiCard_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                        .setTitleText("WARNING")
                                        .setContentText("Meiji card file not found!")
                                        .show();
                            }
                            break;

                        case AREA_CHANGE_NOTIFY_REQUEST:
                            Log.d(getString(R.string.tag), "cmd : AREA_CHANGE_NOTIFY_REQUEST");

                            j_ext = new JSONObject(jsonObject.getString("ext"));
                            String user_id = j_ext.getString("user_id");
                            String device_id = j_ext.getString("device_id");
                            String device_type = j_ext.getString("device_type");
                            String str_stage = j_ext.getString("area");
                            Log.d(getString(R.string.tag), "AREA_CHANGE :" + user_id + "|" + device_id + "|" + device_type + "|" + str_stage);

                            Settings.setArea_stage(str_stage);

                            WsClient.getInstance().sendMessage(
                                    WsProtocol.encapsulation(
                                            WsProtocol.COMMAND.AREA_CHANGE_NOTIFY_ACK.toString(),
                                            j_ext
                                    )
                            );
                            if (!str_stage.equals("RECEIVING") ) {
                                finish();
                            }
                            break;

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

    @Override
    public void onFinished(String result) {

    }
}