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.app.DatePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
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.List_Class.Staging_list;
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.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

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

public class Staging_Activity extends AppCompatActivity implements View.OnClickListener, MessageListener, CallbackListener {
    TextView txt_HT;
    Spinner spinner_status;
    Button btn_search;
    RecyclerView view_staging;
    SimpleDateFormat dt_format;
    Calendar calendar;
    EditText edt_model, edt_dest, edt_pc_no, edt_type, edt_packing_date, edt_packing_line;
    String str_dt, str_today, str_status, str_outer_plan_dt, str_uset_id, str_stage;
    int position;
    WsClient wsClient;
    ArrayList<String> list_status;
    List<Staging_list> staging_list;
    Staging_Adapter staging_adapter;


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

        dt_format = new SimpleDateFormat("yyyy-MM-dd");
        calendar = Calendar.getInstance();
        calendar = (Calendar) calendar.clone();
        str_today = dt_format.format(calendar.getTime());
        Log.d(getString(R.string.tag), "datetime_to_server: " + str_today);

        list_status = new ArrayList<String>();
        staging_list = new ArrayList<Staging_list>();

        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_model = (EditText) findViewById(R.id.edt_model);
        edt_dest = (EditText) findViewById(R.id.edt_dest);
        edt_pc_no = (EditText) findViewById(R.id.edt_pclot);
        edt_type = (EditText) findViewById(R.id.edt_type);
        edt_packing_line = (EditText) findViewById(R.id.edt_packing_line);

        edt_packing_date = (EditText) findViewById(R.id.edt_packing_date);
        edt_packing_date.setText(str_today);
        edt_packing_date.setInputType(InputType.TYPE_NULL);

        edt_packing_date.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final Calendar currentDate = Calendar.getInstance();
                new DatePickerDialog(Staging_Activity.this, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                        currentDate.set(Calendar.YEAR,year);
                        currentDate.set(Calendar.MONTH,monthOfYear);
                        currentDate.set(Calendar.DATE,dayOfMonth);
                        str_dt = dt_format.format(currentDate.getTime());
                        edt_packing_date.setText(str_dt);
                        Log.d(getString(R.string.tag), "packing_date "+str_dt);
                    }
                }, currentDate.get(Calendar.YEAR), currentDate.get(Calendar.MONTH), currentDate.get(Calendar.DATE)).show();
            }
        });

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

//        Get_Status();
        Get_Schedule("" , str_today);
    }

    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.this, SweetAlertDialog.WARNING_TYPE)
                            .setTitleText("WARNING")
                            .setContentText("Please enter receive 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_model.setText("");
                edt_dest.setText("");
                edt_pc_no.setText("");
                edt_type.setText("");
                edt_packing_date.setText(str_today);
                edt_packing_line.setText("");
                spinner_status.setSelection(0);

                staging_list.clear();
                staging_adapter = new Staging_Adapter(staging_list,
                        Staging_Activity.this,
                        "",
                        "0",
                        "");
                view_staging.setAdapter(staging_adapter);
                break;

            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(Staging_Activity.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();
                    }
                }

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

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

        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "get_staging");
            json.put("outer_plan_date", outer_plan_dt);
            json.put("model_no", edt_model.getText().toString().trim());
            json.put("dist", edt_dest.getText().toString().trim());
            json.put("pc_no", edt_pc_no.getText().toString().trim());
            json.put("model_type", edt_type.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.clear();
                            Toast.makeText(Staging_Activity.this,"Not found schedule",Toast.LENGTH_SHORT).show();

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

                                staging_list.add(new Staging_list(
                                        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("receive_plan_qty").equals("null") ? "0" : jArray.getJSONObject(i).getString("receive_plan_qty"),
                                        jArray.getJSONObject(i).getString("receive_act_qty").equals("null") ? "0" : jArray.getJSONObject(i).getString("receive_act_qty"),
                                        jArray.getJSONObject(i).getString("receive_balance").equals("null") ? "0" : jArray.getJSONObject(i).getString("receive_balance"),
                                        jArray.getJSONObject(i).getString("staging_plan_qty").equals("null") ? "0" : jArray.getJSONObject(i).getString("staging_plan_qty"),
                                        jArray.getJSONObject(i).getString("staging_act_qty").equals("null") ? "0" : jArray.getJSONObject(i).getString("staging_act_qty"),
                                        jArray.getJSONObject(i).getString("staging_balance").equals("null") ? "0" : jArray.getJSONObject(i).getString("staging_balance")));
                            }
                        }
                        staging_adapter = new Staging_Adapter(staging_list,
                                                     Staging_Activity.this,
                                                            String.valueOf(position),
                                                            edt_packing_line.getText().toString().trim(),
                                                            edt_packing_date.getText().toString().trim());
                        view_staging.setAdapter(staging_adapter);

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


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

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

                                Intent i = new Intent(getApplicationContext(),MainActivity.class);
                                startActivity(i);
                                finish();

                            }
                            break;

                        case RESET_ACK:

                            break;
                    }
                } catch (JSONException e) {
                    new SweetAlertDialog(Staging_Activity.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
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.d("onActivityResult2", String.valueOf(requestCode+"|"+resultCode));

        if (resultCode == Activity.RESULT_OK){
            finish();
        }
    }

    @Override
    public void onFinished(String result) {

    }

}