package kr.co.compcareworker.Fragment.Enterprise.ServiceList;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.HashMap;

import kr.co.compcareworker.Activity.FragmentActivity;
import kr.co.compcareworker.Data.ArrayItem;
import kr.co.compcareworker.Data.ServiceList.ServiceData;
import kr.co.compcareworker.R;
import kr.co.compcareworker.Util.Adapter.ServiceListRecyclerAdapter;
import kr.co.compcareworker.Util.Api.ApiClient;

import static android.content.Context.INPUT_METHOD_SERVICE;

@SuppressLint("ValidFragment")
public class Service_Fragment extends Fragment {
    private Handler handler, hdr;

    FragmentActivity fa;

    TextView countText, find;
    EditText findText;
    TextView sort;
    RecyclerView list;
    TextView noneList;
    ServiceListRecyclerAdapter adapter;
    String sortType = "wo_memo";

    Boolean first = true;

    ArrayItem<ServiceData> items;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        fa = (FragmentActivity) getActivity();
    }

    @Override
    public void onDetach() {
        super.onDetach();
        fa = null;
    }

    @SuppressLint("ValidFragment")
    public Service_Fragment(Handler handler) {
        this.handler = handler;
    }

    public Service_Fragment() {
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.frag_service, container, false);

        countText = v.findViewById(R.id.countText);
        find = v.findViewById(R.id.find);
        findText = v.findViewById(R.id.findText);
        sort = v.findViewById(R.id.sort);
        list = v.findViewById(R.id.list);
        noneList = v.findViewById(R.id.noneList);

        adapter = new ServiceListRecyclerAdapter(getContext());
        list.setAdapter(adapter);

        findText.setImeOptions(EditorInfo.IME_ACTION_DONE);

        init_Handler();
        init_Listener();

        Get_Contents();

        return v;
    }

    void Get_Contents() {
        HashMap<String, String> data = new HashMap<>();
        data.put("ag_idx", fa.userItem.getArrayitem().getAgIdx());
        data.put("cp_idx", fa.enterpriseItem.getArrayitem().getCpIdx());
        data.put("sfield", sortType);
        data.put("skeyword", findText.getText().toString());
        new ApiClient(data, "proc_worker_list_log", hdr);
    }

    void Set_Contents() {
        countText.setText(items.getArrayitem().size() + "");
        adapter.pt_name = fa.enterpriseItem.getArrayitem().getPtName();
        adapter.cp_idx = fa.enterpriseItem.getArrayitem().getCpIdx();
        ArrayList<ServiceData> data = new ArrayList<>();
        data.addAll(items.getArrayitem());
        adapter.addItem(data);
        first = false;
    }

    void init_Handler() {
        hdr = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg.what == -1) {
                    Toast.makeText(getContext(), msg.obj.toString().replace("\"", ""), Toast.LENGTH_SHORT).show();

                } else if (msg.what == 1) {
                    String url = msg.getData().getString("url");
                    if (url.equals("proc_worker_list_log")) {
                        JsonElement element = new JsonParser().parse(msg.obj.toString());
                        JsonObject result_item = element.getAsJsonObject();
                        items = new Gson().fromJson(result_item, new TypeToken<ArrayItem<ServiceData>>() {
                        }.getType());

                        if (items.isSuccess()) {
                            noneList.setVisibility(View.GONE);
                            list.setVisibility(View.VISIBLE);
                            Set_Contents();
                        } else {
                            noneList.setVisibility(View.VISIBLE);
                            list.setVisibility(View.GONE);
                            Toast.makeText(getContext(), items.getMessage(), Toast.LENGTH_LONG).show();
                            adapter.clearItem();
                            //if (first) getActivity().finish();
                        }
                    }
                }
            }
        };
    }

    private void init_Listener() {
        sort.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String[] str = new String[]{"접수내용", "AIRLINE"};
                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getContext(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
                alertDialogBuilder.setSingleChoiceItems(str, 0, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, final int which) {
                        sort.setText(str[which] + " ▼");
                        if (which == 0) {
                            sortType = "wo_memo";
                            findText.setText("");
                            findText.setInputType(InputType.TYPE_CLASS_TEXT);
                            findText.setHint("접수내용을 입력하세요.");
                        } else {
                            sortType = "cp_airline";
                            findText.setText("");
                            findText.setInputType(InputType.TYPE_CLASS_TEXT);
                            findText.setHint("AIRLINE 을 입력하세요.");
                        }
                        dialog.dismiss();
                    }
                });

                alertDialogBuilder.show();
            }
        });

        find.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                InputMethodManager imm = (InputMethodManager) getContext().getSystemService(INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(findText.getWindowToken(), 0);
                Get_Contents();
            }
        });

        findText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    find.performClick();
                    InputMethodManager imm = (InputMethodManager) getContext().getSystemService(INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(findText.getWindowToken(), 0);
                    return true;
                }
                return false;
            }
        });
    }
}
