package com.tomas.ckd_system;

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

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
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 com.tomas.ckd_system.Adapter.Staging_Adapter;
import com.tomas.ckd_system.Adapter.Staging_Adapter_PC;
import com.tomas.ckd_system.List_Class.Staging_list;
import com.tomas.ckd_system.List_Class.Staging_list_pc;
import com.tomas.ckd_system.lib.Settings;
import com.tomas.ckd_system.lib.common.AsyncHttpClient;
import com.tomas.ckd_system.lib.common.CallbackListener;
import com.tomas.ckd_system.lib.common.MessageListener;

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

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

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

public class Staging_Activity_PC extends AppCompatActivity implements View.OnClickListener, MessageListener, CallbackListener {
    TextView txt_HT;
    Spinner spinner_status;
    RecyclerView view_staging_pc;
    String str_pc_no, str_outer_plan_dt, str_model_no, str_model_type, str_dist, str_status, str_uset_id,
            str_line_no, str_status_position;
    EditText edt_model, edt_dest, edt_pclot, edt_type, edt_packing_date, edt_packing_line;
    Bundle bundle;
    int position;
    WsClient wsClient;
    Button btn_search;

    List<Staging_list_pc>staging_list_pc;
    Staging_Adapter_PC staging_adapter_pc;
    ArrayList<String> list_status;
    InputMethodManager imm;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_staging_pc);
        // update MessageListener class
        WsClient.getInstance().setOnMessageListener(this);
        imm = (InputMethodManager)getSystemService(Staging_Activity_PC.this.INPUT_METHOD_SERVICE);
        str_uset_id = Settings.getLoginUser().getName();

        bundle = getIntent().getExtras();
        str_pc_no = bundle.getString("pc_no");
        str_outer_plan_dt = bundle.getString("outer_plan_date");
        str_dist = bundle.getString("dist");
        str_model_no = bundle.getString("model_no");
        str_model_type = bundle.getString("model_type");
        str_line_no = bundle.getString("line_no");
        str_status_position = bundle.getString("status");


        Log.d(getString(R.string.tag), "bundle: " + str_pc_no);

        list_status = new ArrayList<String>();
        staging_list_pc = new ArrayList<Staging_list_pc>();

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

        btn_search = (Button)findViewById(R.id.btn_search);
        btn_search.setEnabled(false);
        btn_search.setBackgroundResource(R.drawable.button_backgroup_gray);

        edt_packing_line = (EditText) findViewById(R.id.edt_packing_line);
        edt_packing_line.setText(str_line_no);

        edt_pclot = (EditText) findViewById(R.id.edt_pclot);
        edt_pclot.setText(str_pc_no);
        edt_pclot.setEnabled(false);

        edt_model = (EditText) findViewById(R.id.edt_model);
        edt_model.setEnabled(false);
        edt_model.setText(str_model_no);

        edt_dest = (EditText) findViewById(R.id.edt_dest);
        edt_dest.setEnabled(false);
        edt_dest.setText(str_dist);

        edt_type = (EditText) findViewById(R.id.edt_type);
        edt_type.setEnabled(false);
        edt_type.setText(str_model_type);

        edt_packing_date = (EditText) findViewById(R.id.edt_packing_date);
        edt_packing_date.setEnabled(false);
        edt_packing_date.setText(str_outer_plan_dt);

        spinner_status = (Spinner) findViewById(R.id.spinner_status);
        spinner_status.setSelection(Integer.parseInt(str_status_position));
        spinner_status.setEnabled(false);

        view_staging_pc = (RecyclerView) findViewById(R.id.view_staging_pc);
        view_staging_pc.setHasFixedSize(true);
        view_staging_pc.setRecycledViewPool(new RecyclerView.RecycledViewPool());
        view_staging_pc.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        view_staging_pc.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        view_staging_pc.setItemAnimator(new DefaultItemAnimator());

//        Get_Status();
        Get_Schedule("" , str_outer_plan_dt);

    }

    public static void hideKeyboard(@NonNull Activity activity) {
        // Check if no view has focus:
        View view = activity.getCurrentFocus();
        if (view != null) {
            InputMethodManager inputManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
            inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_search:
                btn_search.setEnabled(false);
                btn_search.setBackgroundResource(R.drawable.button_backgroup_gray);

                hideKeyboard(this);
                str_status = spinner_status.getSelectedItem().toString().trim();
                position = spinner_status.getSelectedItemPosition();
                Log.d(getString(R.string.tag), "spinner SelectedItemPosition: "+String.valueOf(position));

                if (str_status.equals("All")) {
                    str_status = "";
                }

                str_outer_plan_dt = edt_packing_date.getText().toString().trim();
                if (str_outer_plan_dt.trim().equals("")) {
                    new SweetAlertDialog(Staging_Activity_PC.this, SweetAlertDialog.WARNING_TYPE)
                            .setTitleText("WARNING")
                            .setContentText("Please enter staging date")
                            .show();
                } else {
                    Get_Schedule(str_status, str_outer_plan_dt);
                }
                break;

            case R.id.btn_clear:
                btn_search.setEnabled(true);
                btn_search.setBackgroundResource(R.drawable.button_backgroup_green);

                edt_pclot.setText(str_pc_no);
                edt_packing_line.setText(str_line_no);
                spinner_status.setSelection(Integer.parseInt(str_status_position));

                staging_list_pc.clear();
                staging_adapter_pc = new Staging_Adapter_PC(staging_list_pc, Staging_Activity_PC.this, str_outer_plan_dt, str_status_position);
                view_staging_pc.setAdapter(staging_adapter_pc);
                break;

            case R.id.btn_main:
                finish();
                break;
        }
    }

    private void Get_Status() {
        list_status.clear();
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "get_status");
            new AsyncHttpClient(getApplicationContext()
                    , Settings.getMgmtList().get("web_api") + "/api_tablet.php"
                    , json.toString()
            ) {
                @Override
                public void onFinished(String response, int resp_code) {
                    Log.d(getString(R.string.tag), "response: " + response);
                    // update mapItems
                    try {
                        JSONArray jArray = new JSONArray(response);
                        Log.d(getString(R.string.tag), "response json length: " + jArray.length());

                        list_status.add("All");
                        for(int i=0;i<jArray.length();i++) {
                            list_status.add(
                                    jArray.getJSONObject(i).getString("status")
                            );
                        }
                        ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>
                                (getApplicationContext(), R.layout.spinner_usr_list, list_status);
                        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                        spinner_status.setAdapter(dataAdapter);

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

    private void Get_Schedule(String status, String outer_plan_dt) {
        staging_list_pc.clear();

        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "get_staging_pc");
            json.put("outer_plan_date", outer_plan_dt);
            json.put("pc_no", str_pc_no);
            json.put("model_no", edt_model.getText().toString().trim());
            json.put("model_type", edt_type.getText().toString().trim());
            json.put("dist", edt_dest.getText().toString().trim());
            json.put("line_no", edt_packing_line.getText().toString().trim());
            json.put("status", status);

            new AsyncHttpClient(getApplicationContext()
                    , Settings.getMgmtList().get("web_api") + "/api_tablet.php"
                    , json.toString()
            ) {
                @Override
                public void onFinished(String response, int resp_code) {
                    Log.d(getString(R.string.tag), "response: " + response);

                    try {
                        JSONArray jArray = new JSONArray(response);
                        Log.d(getString(R.string.tag), "response json length: " + jArray.length());

                        if (jArray.length()==0){
                            staging_list_pc.clear();
                            Toast.makeText(Staging_Activity_PC.this,"Not found schedule",Toast.LENGTH_SHORT).show();

                        }else {
                            for (int i = 0; i < jArray.length(); i++){

                                staging_list_pc.add(new Staging_list_pc(
                                        String.valueOf(i+1),
                                        jArray.getJSONObject(i).getString("dist").trim().equals("null") ? "" : jArray.getJSONObject(i).getString("dist"),
                                        jArray.getJSONObject(i).getString("model_no").trim().equals("null") ? "" : jArray.getJSONObject(i).getString("model_no"),
                                        jArray.getJSONObject(i).getString("model_type").trim().equals("null") ? "" : jArray.getJSONObject(i).getString("model_type"),
                                        jArray.getJSONObject(i).getString("pc_no").trim().equals("null") ? "" : jArray.getJSONObject(i).getString("pc_no"),
                                        jArray.getJSONObject(i).getString("control_no"),
                                        jArray.getJSONObject(i).getString("c_no").trim().equals("null") ? "" : jArray.getJSONObject(i).getString("c_no"),
                                        jArray.getJSONObject(i).getString("line_no")));
                            }
                        }
                        staging_adapter_pc = new Staging_Adapter_PC(staging_list_pc, Staging_Activity_PC.this, outer_plan_dt, str_status_position);
                        view_staging_pc.setAdapter(staging_adapter_pc);

                        btn_search.setEnabled(true);
                        btn_search.setBackgroundResource(R.drawable.button_backgroup_green);


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

    @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 DATA_REDRAW_REQUEST:
                            spinner_status.setSelection(position);
                            str_status = spinner_status.getSelectedItem().toString().trim();
                            if (str_status.equals("All")) {
                                str_status = "";
                            }

                            str_outer_plan_dt = edt_packing_date.getText().toString().trim();
                            Get_Schedule(str_status, str_outer_plan_dt);

                            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("STAGING") ) {

                                Intent resultIntent = new Intent();
                                setResult(Activity.RESULT_OK, resultIntent);
                                finish();
                            }

                            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 RESET_ACK:

                            break;
                    }
                } catch (JSONException e) {
                    new SweetAlertDialog(Staging_Activity_PC.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 onFinished(String result) {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.d("onActivityResult3", String.valueOf(requestCode+"|"+resultCode));
        if (resultCode == Activity.RESULT_OK){
            Intent resultIntent = new Intent();
            setResult(Activity.RESULT_OK, resultIntent);
            finish();
        }

    }
}