package com.tomas.ckd_system;

import static com.tomas.ckd_system.WsProtocol.COMMAND.RESET_REQUEST;
import static com.tomas.ckd_system.lib.ErrorCode.E101;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
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.Outer_Adapter;
import com.tomas.ckd_system.List_Class.Outer_list;
import com.tomas.ckd_system.lib.ProductionSchedule;
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 Outer_Activity extends AppCompatActivity implements View.OnClickListener, ClickRowItemOuter, CallbackListener, MessageListener {
    TextView txt_HT;
    EditText edt_password;
    Spinner spinner_status, spinner_line;
    RecyclerView view_outer;
    SimpleDateFormat dt_format;
    Calendar calendar;
    ConstraintLayout layout_require_access_grant, layout_outer;
//    EditText edt_code_maker, edt_part_no, edt_part_name, edt_color, edt_date, edt_po;
    EditText edt_dist, edt_model, edt_control, edt_pc_no, edt_pk_date, edt_van_date;
    String str_today, str_pk_dt, str_van_dt, str_outer_plan_dt, str_status, btn_focus = "", str_uset_id, str_line_no,
            str_dept_id, str_password_check;
    Button btn_stop_case, btn_subl_cf, btn_leader_cf, btn_search;
    boolean stop_case, subl_cf, leader_cf;
    int position_status, position_line;

    WsClient wsClient;
    ArrayList<String> list_line;
    List<Outer_list> outer_list;
    Outer_Adapter outer_adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_outer);
        // update MessageListener class
        WsClient.getInstance().setOnMessageListener(this);
        layout_outer = (ConstraintLayout)findViewById(R.id.layout_outer);
//        layout_require_access_grant = (ConstraintLayout)findViewById(R.id.layout_require_access_grant);

        str_uset_id = Settings.getLoginUser().getName();
        str_dept_id = Settings.getLoginUser().getDepartment();
//        Str_Line_no = Settings.getLine_no();
//        Log.d(getString(R.string.tag), "getLoginUser: " + str_uset_id+"|"+str_dept_id+"|"+Str_Line_no);


//        edt_password = (EditText)findViewById(R.id.edt_password);
//        str_password_check = "";

        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_line = new ArrayList<String>();
        outer_list = new ArrayList<Outer_list>();

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

//        txt_line_no = (TextView)findViewById(R.id.txt_line_no);
//        txt_line_no.setText("LINE "+Str_Line_no);

//        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_dist = (EditText) findViewById(R.id.edt_dist);
        edt_model = (EditText) findViewById(R.id.edt_model);
        edt_control = (EditText) findViewById(R.id.edt_control);
        edt_pc_no = (EditText) findViewById(R.id.edt_pc_no);


        edt_pk_date = (EditText) findViewById(R.id.edt_pk_date);
        edt_pk_date.setText(str_today);
        edt_pk_date.setInputType(InputType.TYPE_NULL);
        edt_pk_date.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final Calendar currentDate = Calendar.getInstance();
                new DatePickerDialog(Outer_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_pk_dt = dt_format.format(currentDate.getTime());
                        edt_pk_date.setText(str_pk_dt);
                        Log.d(getString(R.string.tag), "packing_date "+str_pk_dt);
                    }
                }, currentDate.get(Calendar.YEAR), currentDate.get(Calendar.MONTH), currentDate.get(Calendar.DATE)).show();
            }
        });

        edt_van_date = (EditText) findViewById(R.id.edt_van_date);
        edt_van_date.setInputType(InputType.TYPE_NULL);
        edt_van_date.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final Calendar currentDate = Calendar.getInstance();
                new DatePickerDialog(Outer_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_van_dt = dt_format.format(currentDate.getTime());
                        edt_van_date.setText(str_van_dt);
                        Log.d(getString(R.string.tag), "van_date "+str_van_dt);
                    }
                }, currentDate.get(Calendar.YEAR), currentDate.get(Calendar.MONTH), currentDate.get(Calendar.DATE)).show();
            }
        });

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

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

        btn_stop_case = (Button)findViewById(R.id.btn_stop_case);
        stop_case = false;

        btn_subl_cf = (Button)findViewById(R.id.btn_subl_cf);
        subl_cf = false;

        btn_leader_cf = (Button)findViewById(R.id.btn_leader_cf);
        subl_cf = false;

        spinner_status = (Spinner) findViewById(R.id.spinner_status);
        spinner_line = (Spinner)findViewById(R.id.spinner_line_no);

        get_line_no();

    }

    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_line_no = spinner_line.getSelectedItem().toString().trim();
                position_line = spinner_line.getSelectedItemPosition();

                str_status = spinner_status.getSelectedItem().toString().trim();
                position_status = spinner_status.getSelectedItemPosition();
                Log.d(getString(R.string.tag), "spinner Position: "+String.valueOf(position_status+" | "+position_line));
                if (str_status.equals("All")){
                    str_status = "";
                }

                Get_Schedule(str_status , edt_pk_date.getText().toString().trim(), str_line_no);


                break;

            case R.id.btn_clear:
                edt_dist.setText("");
                edt_model.setText("");
                edt_control.setText("");
                edt_pc_no.setText("");
                edt_pk_date.setText(str_today);
                edt_van_date.setText("");
                spinner_status.setSelection(0);

                outer_list.clear();
                outer_adapter = new Outer_Adapter(outer_list, Outer_Activity.this, Outer_Activity.this);
                view_outer.setAdapter(outer_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(Outer_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();
                    }
                }
                Settings.setLine_no("");
                finish();
                break;

            case R.id.btn_stop_case:
                    if (stop_case == false) {
                        btn_focus = "stop_case";
                        stop_case = true;
                        btn_stop_case.setBackgroundResource(R.drawable.button_backgroup_green);
                        subl_cf = false;
                        btn_subl_cf.setBackgroundResource(R.drawable.button_backgroup_gray);
                        leader_cf = false;
                        btn_leader_cf.setBackgroundResource(R.drawable.button_backgroup_gray);

                    } else {
                        btn_focus = "";
                        stop_case = false;
                        btn_stop_case.setBackgroundResource(R.drawable.button_backgroup_gray);
                    }
                break;

            case R.id.btn_subl_cf:
                    if (subl_cf == false) {
                        btn_focus = "subl_cf";
                        subl_cf = true;
                        btn_subl_cf.setBackgroundResource(R.drawable.button_backgroup_green);
                        leader_cf = false;
                        btn_leader_cf.setBackgroundResource(R.drawable.button_backgroup_gray);
                        stop_case = false;
                        btn_stop_case.setBackgroundResource(R.drawable.button_backgroup_gray);
                    } else {
                        btn_focus = "";
                        subl_cf = false;
                        btn_subl_cf.setBackgroundResource(R.drawable.button_backgroup_gray);
                    }
                break;

            case R.id.btn_leader_cf:
                Log.d(getString(R.string.tag), "btn_leader_cf: "+String.valueOf(btn_leader_cf));

                    if (leader_cf == false) {
                        btn_focus = "leader_cf";
                        leader_cf = true;
                        btn_leader_cf.setBackgroundResource(R.drawable.button_backgroup_green);
                        stop_case = false;
                        btn_stop_case.setBackgroundResource(R.drawable.button_backgroup_gray);
                        subl_cf = false;
                        btn_subl_cf.setBackgroundResource(R.drawable.button_backgroup_gray);

                    } else {
                        btn_focus = "";
                        leader_cf = false;
                        btn_leader_cf.setBackgroundResource(R.drawable.button_backgroup_gray);
                    }
                break;

//            case R.id.btn_close_view_choice_pdf:
//                layout_require_access_grant.setVisibility(View.GONE);
//                layout_outer.setVisibility(View.VISIBLE);
//                break;


//            case R.id.btn_ok:
//                layout_require_access_grant.setVisibility(View.GONE);
//                layout_outer.setVisibility(View.VISIBLE);
//
//                //check password;
//                String str_password = edt_password.getText().toString().trim();
//                if (!str_password.equals("")){
//                    //check password = user_is -> dep_id == Leader or Sub leader;
//                    Check_Permission(str_password);
//                }
//                break;
        }
    }

//    private void Check_Permission(String password) {
//        try {
//            JSONObject json = new JSONObject();
//            json.put("cmd", "check_user");
//            json.put("id", password);
//            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());
//
//                        for(int i=0;i<jArray.length();i++) {
//
//                            str_password_check = jArray.getJSONObject(i).getString("dept_id");
//
//                        }
//                        if (str_password_check.trim().equals("Leader")||str_password_check.trim().equals("Sub leader")){
//
//                            permission_stopcase = true;
//
//                                btn_focus = "stop_case";
//                                stop_case = true;
//                                btn_stop_case.setBackgroundResource(R.drawable.button_backgroup_green);
//                                subl_cf = false;
//                                btn_subl_cf.setBackgroundResource(R.drawable.button_backgroup_gray);
//                                leader_cf = false;
//                                btn_leader_cf.setBackgroundResource(R.drawable.button_backgroup_gray);
//
//
//                        }else{
//                            permission_stopcase = false;
//                            new SweetAlertDialog(Outer_Activity.this, SweetAlertDialog.WARNING_TYPE)
//                                    .setTitleText("WARNING")
//                                    .setContentText("Not allowed")
//                                    .show();
//                        }
//
//                    } catch (JSONException e) {
//                        e.printStackTrace();
//                    }
//                }
//            }.execute();
//        } catch (JSONException e) {
//            e.printStackTrace();
//        }
//    }

    private void get_line_no() {
        list_line.clear();
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "get_line_no");
            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());

                        for(int i=0;i<jArray.length();i++) {
                            list_line.add(
                                    jArray.getJSONObject(i).getString("line_no")
                            );
                        }
                        ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>
                                (getApplicationContext(), R.layout.spinner_line_list, list_line);
                        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                        spinner_line.setAdapter(dataAdapter);

                        str_line_no = spinner_line.getSelectedItem().toString().trim();
                        Log.d(getString(R.string.tag), "str_line_no: " + str_line_no);

                        Get_Schedule("" , str_today, str_line_no);

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

    private void Get_Schedule(String status, String outer_plan_date, String line_no) {
        outer_list.clear();

        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "get_outer2");
            json.put("outer_plan_date", outer_plan_date);
            json.put("line_no", line_no);
            json.put("dist", edt_dist.getText().toString().trim());
            json.put("model_no", edt_model.getText().toString().trim());
            json.put("control_no", edt_control.getText().toString().trim());
            json.put("pc_no", edt_pc_no.getText().toString().trim());
            json.put("van_date", edt_van_date.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){
                            outer_list.clear();
                            Toast.makeText(Outer_Activity.this,"Not found schedule",Toast.LENGTH_SHORT).show();

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

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

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

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

                                }

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

                                String leader_cf =  jArray.getJSONObject(i).getString("outer_lead_cf_user_id").trim().equals("null") ? "" : jArray.getJSONObject(i).getString("outer_lead_cf_user_id");

                                String str_result = "";
                                    if (!leader_cf.trim().equals("")){
                                        count_complete = count_complete + 1;
                                        str_result = String.valueOf(count_complete);

                                    }else{
                                        str_result = "";
                                    }

                                    outer_list.add(new Outer_list(
                                            outer_plan_date,
                                            jArray.getJSONObject(i).getString("pc_no"),
                                            jArray.getJSONObject(i).getString("model_no").trim().equals("null") ? "" : jArray.getJSONObject(i).getString("model_no"),
                                            jArray.getJSONObject(i).getString("dist").trim().equals("null") ? "" : jArray.getJSONObject(i).getString("dist"),
                                            jArray.getJSONObject(i).getString("control_no"),
                                            jArray.getJSONObject(i).getString("cont_no").trim().equals("null") ? "" : jArray.getJSONObject(i).getString("cont_no"),
                                            vanning_plan_date,
                                            jArray.getJSONObject(i).getString("case_no"),
                                            jArray.getJSONObject(i).getString("status"),
                                            outer_start_dt,
                                            outer_act_dt,
                                            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("receive_user_id").trim().equals("null") ? "" : jArray.getJSONObject(i).getString("receive_user_id"),
                                            jArray.getJSONObject(i).getString("staging_plan_qty").trim().equals("null") ? "0" : jArray.getJSONObject(i).getString("staging_plan_qty"),
                                            jArray.getJSONObject(i).getString("staging_act_qty").trim().equals("null") ? "0" : jArray.getJSONObject(i).getString("staging_act_qty"),
                                            jArray.getJSONObject(i).getString("staging_user_id").trim().equals("null") ? "" : jArray.getJSONObject(i).getString("staging_user_id"),
                                            jArray.getJSONObject(i).getString("inner_plan_qty").trim().equals("null") ? "0" : jArray.getJSONObject(i).getString("inner_plan_qty"),
                                            jArray.getJSONObject(i).getString("inner_act_qty").trim().equals("null") ? "0" : jArray.getJSONObject(i).getString("inner_act_qty"),
                                            jArray.getJSONObject(i).getString("inner_user_id").trim().equals("null") ? "" : jArray.getJSONObject(i).getString("inner_user_id"),
                                            jArray.getJSONObject(i).getString("outer_plan_qty").trim().equals("null") ? "0" : jArray.getJSONObject(i).getString("outer_plan_qty"),
                                            jArray.getJSONObject(i).getString("outer_act_qty").trim().equals("null") ? "0" : jArray.getJSONObject(i).getString("outer_act_qty"),
                                            jArray.getJSONObject(i).getString("outer_user_id").trim().equals("null") ? "" : jArray.getJSONObject(i).getString("outer_user_id"),
                                            jArray.getJSONObject(i).getString("outer_subl_cf_user_id").trim().equals("null") ? "" : jArray.getJSONObject(i).getString("outer_subl_cf_user_id"),
                                            leader_cf,
                                            str_result,
                                            jArray.getJSONObject(i).getString("stage")));
//                                }
                            }
                        }
                        outer_adapter = new Outer_Adapter(outer_list, Outer_Activity.this,Outer_Activity.this );
                        view_outer.setAdapter(outer_adapter);

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

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

    @Override
    public void SelectionItemRowOuter(String pc_no, String control_no, String case_no, String leader,
                                      String sub_leader, String outer_act, String outer_plan, String status) {

        Log.d(getString(R.string.tag), "SelectionItemRowOuter: " + case_no);

        if (btn_focus.trim().equals(""))
            return;

        int int_outer_act, int_outer_plan;
        int_outer_act = Integer.parseInt(outer_act);
        int_outer_plan = Integer.parseInt(outer_plan);

        if(btn_focus.trim().equals("stop_case")){
            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("event", WsProtocol.EVENT.TB_OUTER_PACKING_STOP_CASE_OPEN);
                j_ext.put("status", ProductionSchedule.STATUS.STOP_CASE);
                j_ext.put("stage", ProductionSchedule.STAGE.OUTER_PACKING);
                j_ext.put("pc_no", pc_no);
                j_ext.put("control_no", control_no);
                j_ext.put("case_no", case_no);
                WsClient.getInstance().sendMessage(
                        WsProtocol.encapsulation(
                                WsProtocol.COMMAND.EVENT_LOG_REQUEST.toString(),
                                j_ext
                        )
                );

            } catch (JSONException e) {
                new SweetAlertDialog(Outer_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();
                }
            }
        }else if (btn_focus.trim().equals("subl_cf")){
//            if (sub_leader.trim().equals("") && status.trim().equals("OUTER_PACKED")){
            if (sub_leader.trim().equals("")&&status.trim().equals("OUTER_PACKED")||status.trim().equals("CANCELED")||status.trim().equals("STOP_CASE")){
                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("event", WsProtocol.EVENT.TB_OUTER_PACKING_SUB_LEADER_CONFIRM_OPEN);
                            j_ext.put("status", ProductionSchedule.STATUS.WORKING);
                            j_ext.put("stage", ProductionSchedule.STAGE.OUTER_PACKING);
                            j_ext.put("pc_no", pc_no);
                            j_ext.put("control_no", control_no);
                            j_ext.put("case_no", case_no);
                            WsClient.getInstance().sendMessage(
                                    WsProtocol.encapsulation(
                                            WsProtocol.COMMAND.EVENT_LOG_REQUEST.toString(),
                                            j_ext
                                    )
                            );

                        } catch (JSONException e) {
                            new SweetAlertDialog(Outer_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();
                            }
                        }

            }else if (!sub_leader.trim().equals("")){
                new SweetAlertDialog(Outer_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                .setTitleText("WARNING")
                                .setContentText("Sub Leader has confirmed this item.")
                                .show();
            }else{
                new SweetAlertDialog(Outer_Activity.this, SweetAlertDialog.WARNING_TYPE)
                        .setTitleText("WARNING")
                        .setContentText("This item status : "+status)
                        .show();
            }


        }else if (btn_focus.trim().equals("leader_cf")){
            if (!leader.trim().equals("")){
                new SweetAlertDialog(Outer_Activity.this, SweetAlertDialog.WARNING_TYPE)
                        .setTitleText("WARNING")
                        .setContentText("Leader has confirmed this item.")
                        .show();

            } else if (sub_leader.trim().equals("")){
                new SweetAlertDialog(Outer_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                .setTitleText("WARNING")
                                .setContentText("Sub Leader hasn't confirmed this item.")
                                .show();
            }else if (!sub_leader.trim().equals("") && leader.trim().equals("") && (status.trim().equals("OUTER_PACKED")||status.trim().equals("STOP_CASE"))){
                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", "TABLET");
                                j_ext.put("event", WsProtocol.EVENT.TB_OUTER_PACKING_LEADER_CONFIRM_OPEN);
                                j_ext.put("status", ProductionSchedule.STATUS.WORKING);
                                j_ext.put("stage", ProductionSchedule.STAGE.OUTER_PACKING);
                                j_ext.put("pc_no", pc_no);
                                j_ext.put("control_no", control_no);
                                j_ext.put("case_no", case_no);
                                WsClient.getInstance().sendMessage(
                                        WsProtocol.encapsulation(
                                                WsProtocol.COMMAND.EVENT_LOG_REQUEST.toString(),
                                                j_ext
                                        )
                                );
                            } catch (JSONException e) {
                                new SweetAlertDialog(Outer_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();
                                }
                            }
            }else{
                new SweetAlertDialog(Outer_Activity.this, SweetAlertDialog.WARNING_TYPE)
                        .setTitleText("WARNING")
                        .setContentText("This item status : "+status)
                        .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 RESET_ACK:

                            break;

                        case DATA_REDRAW_REQUEST:
//                            ReQuery_schedule();

                            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("OUTER") ) {
                                finish();
                            }
                            break;

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

                            btn_search.setEnabled(false);
                            btn_search.setBackgroundResource(R.drawable.button_backgroup_gray);

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

                            WsClient.getInstance().sendMessage(
                                    WsProtocol.encapsulation(
                                            WsProtocol.COMMAND.OUTER_LINE_NOTIFY_ACK.toString(),
                                            j_ext
                                    )
                            );
//
//                            Settings.setLine_no(line_no);
//                            Str_Line_no = line_no;
//                            txt_line_no.setText("LINE "+Str_Line_no);

                            ReQuery_schedule();

                            break;

                        case EVENT_LOG_ACK:
                            new SweetAlertDialog(Outer_Activity.this, SweetAlertDialog.NORMAL_TYPE)
                                    .setTitleText("Alert")
                                    .setContentText("Please use handy to confirm.")
                                    .show();
                    }
                } catch (JSONException e) {
                    new SweetAlertDialog(Outer_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();
                    }
                }
            }
        });
    }


    private void ReQuery_schedule() {
        spinner_line.setSelection(position_line);
        str_line_no = spinner_line.getSelectedItem().toString().trim();

        spinner_status.setSelection(position_status);
        str_status = spinner_status.getSelectedItem().toString().trim();
        if (str_status.equals("All")) {
            str_status = "";
        }

        Get_Schedule(str_status , edt_pk_date.getText().toString().trim(), str_line_no);

    }

    private void Re_Connected() {


    }

    @Override
    public void onFinished(String result) {

    }
}