package com.tomas.ckd_system;

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

import androidx.annotation.NonNull;
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.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.Receiving_Adapter;
import com.tomas.ckd_system.List_Class.Receiving_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 Receiving_Activity extends AppCompatActivity implements View.OnClickListener , MessageListener, CallbackListener {
    TextView txt_HT;
    Spinner spinner_status;
    RecyclerView view_schedule;
    SimpleDateFormat dt_format;
    Calendar calendar;
    EditText edt_code_maker, edt_part_no, edt_part_name, edt_color, edt_date, edt_po;
    String str_dt, str_today, str_status, str_receive_plan_date, str_uset_id;
    Button btn_search;
    int position;

    ArrayList<String> list_status;
    List<Receiving_list> receiving_lists;
    Receiving_Adapter receiving_adapter;
    WsClient wsClient;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_receiving);
        // 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>();
        receiving_lists = new ArrayList<Receiving_list>();

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

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

        edt_code_maker = (EditText) findViewById(R.id.edt_code_maker);
        edt_part_no = (EditText) findViewById(R.id.edt_part_no);
        edt_part_name = (EditText) findViewById(R.id.edt_part_name);
        edt_color = (EditText) findViewById(R.id.edt_color);
        edt_po = (EditText) findViewById(R.id.edt_po);

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

        edt_date.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final Calendar currentDate = Calendar.getInstance();
                new DatePickerDialog(Receiving_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_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_schedule = (RecyclerView) findViewById(R.id.view_receiving);
        view_schedule.setHasFixedSize(true);
        view_schedule.setRecycledViewPool(new RecyclerView.RecycledViewPool());
        view_schedule.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        view_schedule.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        view_schedule.setItemAnimator(new DefaultItemAnimator());

        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_receive_plan_date = edt_date.getText().toString().trim();
                Get_Schedule(str_status, str_receive_plan_date);
                break;

            case R.id.btn_clear:
                btn_search.setEnabled(true);
                btn_search.setBackgroundResource(R.drawable.button_backgroup_green);
                edt_code_maker.setText("");
                edt_part_no.setText("");
                edt_part_name.setText("");
                edt_color.setText("");
                edt_date.setText(str_today);
                edt_po.setText("");
                spinner_status.setSelection(0);

                receiving_lists.clear();
                receiving_adapter = new Receiving_Adapter(receiving_lists, Receiving_Activity.this);
                view_schedule.setAdapter(receiving_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(Receiving_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(Receiving_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();
        } catch (JSONException e) {
            new SweetAlertDialog(Receiving_Activity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage())
                    .show();
        }
    }

    private void Get_Schedule(String status, String receive_plan_date) {
        receiving_lists.clear();

        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "get_receive");
            json.put("receive_plan_date", receive_plan_date);
            json.put("maker_code", edt_code_maker.getText().toString().trim());
            json.put("part_no", edt_part_no.getText().toString().trim());
            json.put("part_name", edt_part_name.getText().toString().trim());
            json.put("part_color", edt_color.getText().toString().trim());
            json.put("po_no", edt_po.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){
                            receiving_lists.clear();
                            Toast.makeText(Receiving_Activity.this,"Not found schedule",Toast.LENGTH_SHORT).show();

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

                                String receive_plan_date = jArray.getJSONObject(i).getString("receive_plan_date");
                                if (receive_plan_date.trim().equals("")||receive_plan_date.trim().equals("null")){
                                    receive_plan_date = "";
                                }else {
                                    JSONObject array_date = obj.getJSONObject("receive_plan_date");
                                    receive_plan_date = array_date.getString("date");
                                    receive_plan_date = receive_plan_date.substring(0,10);
                                }

                                String receive_act_dt = jArray.getJSONObject(i).getString("receive_act_dt");
                                if (receive_act_dt.trim().equals("")||receive_act_dt.trim().equals("null")){
                                    receive_act_dt = "";
                                }else {
                                    JSONObject array_date = obj.getJSONObject("receive_act_dt");
                                    receive_act_dt = array_date.getString("date");
                                    receive_act_dt = receive_act_dt.substring(0,19);
                                }

                                receiving_lists.add(new Receiving_list(
                                        String.valueOf(i+1),
                                        jArray.getJSONObject(i).getString("po_no"),
                                        jArray.getJSONObject(i).getString("part_no"),
                                        receive_plan_date,
                                        jArray.getJSONObject(i).getString("receive_plan_qty").trim().equals("null") ? "0" : jArray.getJSONObject(i).getString("receive_plan_qty"),
                                        jArray.getJSONObject(i).getString("receive_act_qty").trim().equals("null") ? "0" : jArray.getJSONObject(i).getString("receive_act_qty"),
                                        jArray.getJSONObject(i).getString("balance").trim().equals("null") ? "0" : jArray.getJSONObject(i).getString("balance"),
                                        jArray.getJSONObject(i).getString("maker_code").trim().equals("null") ? "" : jArray.getJSONObject(i).getString("maker_code"),
                                        jArray.getJSONObject(i).getString("maker_name").trim().equals("null") ? "" : jArray.getJSONObject(i).getString("maker_name"),
                                        jArray.getJSONObject(i).getString("part_name").trim().equals("null") ? "" : jArray.getJSONObject(i).getString("part_name"),
                                        jArray.getJSONObject(i).getString("part_color").trim().equals("null") ? "" : jArray.getJSONObject(i).getString("part_color"),
                                        jArray.getJSONObject(i).getString("receive_plan_time").trim().equals("null") ? "" : jArray.getJSONObject(i).getString("receive_plan_time"),
                                        receive_act_dt,
                                        jArray.getJSONObject(i).getString("receive_step1").trim().equals("null") ? "" : jArray.getJSONObject(i).getString("receive_step1"),
                                        jArray.getJSONObject(i).getString("receive_user_id").trim().equals("null") ? "" : jArray.getJSONObject(i).getString("receive_user_id"),
                                        jArray.getJSONObject(i).getString("status")));
                            }
                        }
                        receiving_adapter = new Receiving_Adapter(receiving_lists, Receiving_Activity.this);
                        view_schedule.setAdapter(receiving_adapter);

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

                    } catch (JSONException e) {
                        new SweetAlertDialog(Receiving_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();
        } catch (JSONException e) {
            new SweetAlertDialog(Receiving_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_receive_plan_date = edt_date.getText().toString().trim();
                            Get_Schedule(str_status, str_receive_plan_date);

                            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");
                            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;

                        case RESET_ACK:

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

    }
}