package kr.co.compcarecompany.Fragment.Main;

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.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
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.HashMap;

import kr.co.compcarecompany.Activity.FragmentActivity;
import kr.co.compcarecompany.Data.ArrayItem_;
import kr.co.compcarecompany.Data.Memo.Login.UserItem;
import kr.co.compcarecompany.R;
import kr.co.compcarecompany.Util.Adapter.MemberManagementAdapter;
import kr.co.compcarecompany.Util.Api.ApiClient;

import static kr.co.compcarecompany.Activity.ActivityBasic.userItem;

public class Member_Management_Fragment extends Fragment {

    private Handler handler;
    private FragmentActivity fa;
    private LinearLayout activated_memberLL, inactivated_memberLL;
    private RecyclerView activated_memberRV, inactivated_memberRV;
    private TextView closeTV;
    private ProgressBar member_managementPB;
    private MemberManagementAdapter activated_adapter, inactivated_adapter;

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

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

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

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

        activated_memberLL = v.findViewById(R.id.activated_memberLL);
        inactivated_memberLL = v.findViewById(R.id.inactivated_memberLL);
        activated_memberRV = v.findViewById(R.id.activated_memberRV);
        inactivated_memberRV = v.findViewById(R.id.inactivated_memberRV);
        closeTV = v.findViewById(R.id.closeTV);
        member_managementPB = v.findViewById(R.id.member_managementPB);

        activated_adapter = new MemberManagementAdapter(getContext(), new MemberManagementAdapter.managementListener() {
            @Override
            public void clickBtn(String mb_id) {
                member_managementPB.setVisibility(View.VISIBLE);
                HashMap<String, String> data = new HashMap<>();
                data.put("mb_id", mb_id);
                //Delete :: 차단
                data.put("type", "D");
                new ApiClient(data, "proc_admin_member_management", handler);
            }
        });

        inactivated_adapter = new MemberManagementAdapter(getContext(), new MemberManagementAdapter.managementListener() {
            @Override
            public void clickBtn(String mb_id) {
                member_managementPB.setVisibility(View.VISIBLE);
                HashMap<String, String> data = new HashMap<>();
                data.put("mb_id", mb_id);
                //Revival :: 차단 해제
                data.put("type", "R");
                new ApiClient(data, "proc_admin_member_management", handler);
            }
        });

        activated_memberRV.setAdapter(activated_adapter);
        inactivated_memberRV.setAdapter(inactivated_adapter);

        init_Handler();
        init_Listener();
        Get_Members();
        return v;
    }

    void init_Listener() {

        // 닫기 버튼
        closeTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (userItem.getArrayitem().getMbActivatedList() == null || userItem.getArrayitem().getMbActivatedList().size() < 1) {
                    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getContext());
                    dialogBuilder.setTitle("콤프케어 작업자");
                    dialogBuilder.setMessage("등록된 멤버가 전부 차단되었습니다.\n로그아웃 시 접속이 제한될 수 있습니다.\n화면을 나가시겠습니까?");
                    dialogBuilder.setPositiveButton("확인", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int i) {
                            dialog.dismiss();
                            fa.finish();
                        }
                    }).setNegativeButton("취소", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int i) {
                            dialog.dismiss();
                        }
                    });
                    dialogBuilder.show();

                } else {
                    fa.finish();
                }
            }
        });
    }

    void Get_Members() {
        member_managementPB.setVisibility(View.VISIBLE);
        HashMap<String, String> data = new HashMap<>();
        data.put("ag_idx", fa.userItem.getArrayitem().getAgIdx());
        data.put("pt_idx", fa.userItem.getArrayitem().getPtIdx());
        data.put("mb_idx", fa.userItem.getArrayitem().getMbIdx());
        new ApiClient(data, "proc_admin_get_member_list", handler);
    }

    private void init_Handler() {
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);

                String url = msg.getData().getString("url");

                if (url.equals("proc_admin_get_member_list")) {
                    JsonElement element = new JsonParser().parse(msg.obj.toString());
                    JsonObject result_item = element.getAsJsonObject();

                    if (result_item.get("resultItem").getAsJsonObject().get("result").getAsString().equals("Y")) {

                        userItem = new Gson().fromJson(result_item, new TypeToken<ArrayItem_<UserItem>>() {
                        }.getType());

                        if (userItem.getArrayitem().getMbActivatedList() != null && userItem.getArrayitem().getMbActivatedList().size() > 0) {
                            activated_adapter.addItem(userItem.getArrayitem().getMbActivatedList());
                            activated_memberLL.setVisibility(View.VISIBLE);
                        } else {
                            activated_adapter.clearItem();
                            activated_memberLL.setVisibility(View.GONE);
                        }

                        if (userItem.getArrayitem().getMbInactivatedList() != null && userItem.getArrayitem().getMbInactivatedList().size() > 0) {
                            inactivated_adapter.addItem(userItem.getArrayitem().getMbInactivatedList());
                            inactivated_memberLL.setVisibility(View.VISIBLE);
                        } else {
                            inactivated_adapter.clearItem();
                            inactivated_memberLL.setVisibility(View.GONE);
                        }

                    } else {
                        Toast.makeText(getContext(), result_item.get("resultItem").getAsJsonObject().get("message").getAsString(), Toast.LENGTH_SHORT).show();
                    }

                } else if (url.equals("proc_admin_member_management")) {
                    JsonElement element = new JsonParser().parse(msg.obj.toString());
                    JsonObject result_item = element.getAsJsonObject();
                    Toast.makeText(getContext(), result_item.get("resultItem").getAsJsonObject().get("message").getAsString(), Toast.LENGTH_SHORT).show();

                    if (result_item.get("resultItem").getAsJsonObject().get("result").getAsString().equals("Y")) {
                        Get_Members();
                    }


                }
                member_managementPB.setVisibility(View.GONE);
            }
        };
    }
}

