package com.tomas.ckd_system;

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

import androidx.appcompat.app.AppCompatActivity;

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

import com.tomas.ckd_system.lib.Device_HT;
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.Set;

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

public class MainActivity extends AppCompatActivity implements View.OnClickListener, MessageListener, CallbackListener {
    TextView txt_user, txt_device, txt_ht;
    String str_stage, Str_MODE = "", str_uset_id;
    Button btn_meiji_card;
    WsClient wsClient;
    Bundle bundle;
    int Request = 2000;

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

        txt_user = (TextView) findViewById(R.id.txt_user);
        txt_user.setText("User : "+ Settings.getLoginUser().getName());
        str_uset_id = Settings.getLoginUser().getName();

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

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

        str_stage = Settings.getArea_stage().toString().trim();

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

    }

    @Override
    protected void onStart() {
        super.onStart();
        str_stage = Settings.getArea_stage().toString().trim();
        Log.d(getString(R.string.tag), "getArea_stage : "+str_stage);

        if (str_stage.trim().equals("RECEIVING")){
            btn_meiji_card.setBackgroundResource(R.drawable.button_backgroup_menu);
            btn_meiji_card.setEnabled(true);
        }else{
            btn_meiji_card.setBackgroundResource(R.drawable.button_backgroup_gray);
            btn_meiji_card.setEnabled(false);
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_logout:
                finishAffinity();
                System.exit(0);
                break;

            case R.id.btn_production_set_part:
                Str_MODE = "PRODUCTION_SCHEDULE_";
                Mode_Request(Str_MODE);
                Intent intent = new Intent(MainActivity.this, ProductionSchedulePacking_Activity.class);
                startActivity(intent);
                break;

            case R.id.btn_production_receive:
                Str_MODE = "PRODUCTION_SCHEDULE_RECEIVE";
                Mode_Request(Str_MODE);
                Intent i = new Intent(MainActivity.this, ProductionScheduleReceive_Activity.class);
                startActivity(i);
                break;
        }

        str_stage = Settings.getArea_stage().toString().trim();
            switch (view.getId()) {
                case R.id.btn_meiji_card:
                    if (str_stage.trim().equals("null")||str_stage.trim().equals("")){
                        new SweetAlertDialog(MainActivity.this, SweetAlertDialog.WARNING_TYPE)
                        .setTitleText("WARNING")
                        .setContentText("Not found area!")
                        .show();

                    }else {
                        Str_MODE = "MEIJI_CARD_DISPLAY";
                        Mode_Request(Str_MODE);
                        Intent i = new Intent(MainActivity.this, MeijiCard_Activity.class);
                        startActivity(i);
                        break;
                    }

                case R.id.btn_monitor:
                    if (str_stage.trim().equals("null")||str_stage.trim().equals("")){
                        new SweetAlertDialog(MainActivity.this, SweetAlertDialog.WARNING_TYPE)
                                .setTitleText("WARNING")
                                .setContentText("Not found area!")
                                .show();

                    }else {
                        Str_MODE = "MONITOR";
                        Mode_Request(Str_MODE);
                        if (str_stage.trim().equals("RECEIVING")) {
                            Intent intent_receiving = new Intent(MainActivity.this, Receiving_Activity.class);
                            startActivity(intent_receiving);

                        } else if (str_stage.trim().equals("STAGING")) {
                            Intent intent_staging = new Intent(MainActivity.this, Staging_Detail_Activity.class);
                            startActivity(intent_staging);
//                            startActivityForResult(intent_staging, 100);


                        } else {
//                    (str_stage.trim().equals("outer"))
                            Intent intent_outer = new Intent(MainActivity.this, Outer_Activity.class);
                            startActivity(intent_outer);

                        }
                    }
                    break;
            }
//        }
    }

    private void Mode_Request(String mode) {
        //sent data to ws
        try {
            JSONObject j_ext;
            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("mode", mode);
            WsClient.getInstance().sendMessage(
                    WsProtocol.encapsulation(
                            WsProtocol.COMMAND.SET_MODE_REQUEST.toString(),
                            j_ext
                    )
            );

        } catch (JSONException e) {
            new SweetAlertDialog(MainActivity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage())
                    .show();
        } catch (Exception e) {
            if (e.getMessage().trim().equals("The server might crash")){
                WsClient.getInstance().connect();
            }
        }
    }

    @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 SET_MODE_ACK:
                            Log.d(getString(R.string.tag), "mode_cmd : SET_MODE_ACK");

                            break;
                        case HELLO:
                            j_ext = new JSONObject(jsonObject.getString("ext"));
                            WsClient.getInstance().client_id = j_ext.getInt("id");

                            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
                                    )
                            );
                            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");
                            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);
                            str_stage = Settings.getArea_stage().toString().trim();
                            if (str_stage.trim().equals("RECEIVING")){
                                btn_meiji_card.setBackgroundResource(R.drawable.button_backgroup_menu);
                                btn_meiji_card.setEnabled(true);
                            }else{
                                btn_meiji_card.setBackgroundResource(R.drawable.button_backgroup_gray);
                                btn_meiji_card.setEnabled(false);
                            }

                            WsClient.getInstance().sendMessage(
                                    WsProtocol.encapsulation(
                                            WsProtocol.COMMAND.AREA_CHANGE_NOTIFY_ACK.toString(),
                                            j_ext
                                    )
                            );
                            break;

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

                            j_ext = new JSONObject(jsonObject.getString("ext"));
                            String line_no = j_ext.getString("line_no");
                            Log.d(getString(R.string.tag), "OUTER_LINE_NOTIFY_REQUEST :" + line_no);

                            Settings.setLine_no(line_no);
                            break;

                        case RESET_ACK:

                            break;

                    }
                } catch (JSONException e) {
                    new SweetAlertDialog(MainActivity.this, SweetAlertDialog.ERROR_TYPE)
                            .setTitleText("ERROR")
                            .setContentText(e.getMessage())
                            .show();
                } catch (Exception e) {
                    if (e.getMessage().trim().equals("The server might crash")){
                        WsClient.getInstance().connect();
                    }
                }
            }
        });
    }

    public void onResume() {
        super.onResume();
        Log.d(getString(R.string.tag), "onResume() on class " + getLocalClassName());

        if (Settings.getLoginUser() == null) return;

        Log.d(getString(R.string.tag), "onResume() on class getLoginUser != null" + getLocalClassName());

        // update MessageListener class
        WsClient client = WsClient.getInstance();
        if (client != null) {
            client.setOnMessageListener(this);

            if (!client.isConnected()) {
                // Connect to web socket server
                if (Settings.getMgmtList().containsKey("ws_node")
                        && Settings.getLoginUser()!=null) {
                    wsClient = WsClient.getInstance(
                            MainActivity.this
                            , MainActivity.this
                            , getApplicationContext()
                            , Settings.getMgmtList().get("ws_node"));
                }
            }

            try {
                JSONObject 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));
                WsClient.getInstance().sendMessage(
                        WsProtocol.encapsulation(
                                RESET_REQUEST.toString(),
                                j_ext
                        )
                );
            } catch (Exception e) {
                if (e.getMessage().trim().equals("The server might crash")){
                    WsClient.getInstance().connect();
                }
            }
        } else {
            // Connect to web socket server
            if (Settings.getMgmtList().containsKey("ws_node")
                    && Settings.getLoginUser()!=null) {
                wsClient = WsClient.getInstance(
                        MainActivity.this
                        , MainActivity.this
                        , getApplicationContext()
                        , Settings.getMgmtList().get("ws_node"));
            }
        }
    }

    @Override
    public void onFinished(String result) {

    }
}