package com.ccwangluo.im.ui.dashboard;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;

import com.ccwangluo.ccim.CCIMClient;
import com.ccwangluo.ccim.listener.ResultEventCallback;
import com.ccwangluo.ccim.modle.Contact;
import com.ccwangluo.ccim.modle.ContactGroup;
import com.ccwangluo.ccim.modle.Dialog;
import com.ccwangluo.ccim.modle.SearchRes;
import com.ccwangluo.ccim.modle.User;
import com.ccwangluo.im.adapter.ContactExpandableAdapter;
import com.ccwangluo.im.data.LoginViewModel;
import com.ccwangluo.im.databinding.FragmentDashboardBinding;
import com.ccwangluo.im.listener.OnContactClickLisener;
import com.ccwangluo.im.util.ToastUtil;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class ContactsFragment extends Fragment {

    private LoginViewModel loginViewModel;
    private FragmentDashboardBinding binding;
    private ContactExpandableAdapter contactExpandableAdapter;
    private List<Contact> contactList = new ArrayList<>();
    private List<ContactGroup> contactGroupList = new ArrayList<>();
    private List<Dialog> dialogList = new ArrayList<>();
    private NavController navController;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {


        binding = FragmentDashboardBinding.inflate(inflater, container, false);
        View root = binding.getRoot();

        loginViewModel =
                new ViewModelProvider(getActivity()).get(LoginViewModel.class);
        contactExpandableAdapter = new ContactExpandableAdapter(getContext(), contactGroupList, contactList, loginViewModel, new OnContactClickLisener() {
            @Override
            public void onClick(Contact contact) {
//                Bundle bundle = new Bundle();
//                bundle.putSerializable("contact", contact);
//                navController.navigate(R.id.navigation_connect, bundle);
                Intent intent = new Intent(getContext(), ConnectActivity.class);
                intent.putExtra("contact", contact);
                startActivity(intent);
            }
        });

        binding.contactList.setAdapter(contactExpandableAdapter);

        loginViewModel.contactList.observe(getViewLifecycleOwner(), new Observer<Collection<Contact>>() {
            @Override
            public void onChanged(Collection<Contact> contacts) {
                contactList.clear();
                contactList.addAll(contacts);
                contactExpandableAdapter.reFreshData(contactGroupList, contactList, dialogList);
            }
        });

        loginViewModel.contactGroupList.observe(getViewLifecycleOwner(), new Observer<Collection<ContactGroup>>() {
            @Override
            public void onChanged(Collection<ContactGroup> contactGroups) {
                contactGroupList.clear();
                contactGroupList.addAll(contactGroups);
                contactExpandableAdapter.reFreshData(contactGroupList, contactList, dialogList);
            }
        });

        loginViewModel.dialogList.observe(getViewLifecycleOwner(), new Observer<Collection<Dialog>>() {
            @Override
            public void onChanged(Collection<Dialog> dialogs) {
                dialogList.clear();
                dialogList.addAll(dialogs);
                contactExpandableAdapter.reFreshData(contactGroupList, contactList, dialogList);
            }
        });

        binding.searchUser.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                LinearLayout linearLayout = new LinearLayout(getContext());
                linearLayout.setOrientation(LinearLayout.VERTICAL);
                final EditText etUserName = new EditText(getContext());
                etUserName.setHint("etUserName");
                final EditText etUserId = new EditText(getContext());
                etUserId.setHint("etUserId");
                linearLayout.addView(etUserName);
                linearLayout.addView(etUserId);
                AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
                builder.setTitle("username").setIcon(android.R.drawable.ic_dialog_info).setView(linearLayout)
                        .setNegativeButton("Cancel", null);
                builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int which) {
                        String userName = etUserName.getText().toString();
                        String userId = etUserId.getText().toString();
                        Long id = 0L;
                        if (!userId.isEmpty()) {
                            id = Long.parseLong(userId);
                        }
                        CCIMClient.getInstance().searchUser(userName, id, 1, 5, new ResultEventCallback<SearchRes>() {
                            @Override
                            public void onSuccess(SearchRes searchRes) {
                                int total = searchRes.getTotal();
                                if (searchRes.getUsers().size() > 0) {
                                    showSearchResultdialog(searchRes.getUsers());
                                }
                            }

                            @Override
                            public void onFailed(int errorCode) {

                            }
                        });
                    }
                });
                builder.show();
            }
        });

        binding.contactReqList.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showContactReqList();
            }
        });

        binding.createGroup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final EditText inputServer = new EditText(getContext());
                AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
                builder.setTitle("groupname").setIcon(android.R.drawable.ic_dialog_info).setView(inputServer)
                        .setNegativeButton("Cancel", null);
                builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int which) {
                        String groupname = inputServer.getText().toString();
                        CCIMClient.getInstance().createContactGroup(groupname, new ResultEventCallback<Long>() {
                            @Override
                            public void onSuccess(Long aLong) {
                                ToastUtil.show(getContext(), "createContactGroup success");
                                loginViewModel.getContactList();
                            }

                            @Override
                            public void onFailed(int errorCode) {
                                ToastUtil.show(getContext(), " onFailed  :" + errorCode);
                            }
                        });
                    }
                });
                builder.show();
            }
        });

        loginViewModel.getContactList();
        return root;
    }

    @Override
    public void onResume() {
        super.onResume();
        navController = Navigation.findNavController(getView());
    }

    private void showContactReqList() {
        CCIMClient.getInstance().getContactReqList(new ResultEventCallback<List<User>>() {
            @Override
            public void onSuccess(List<User> users) {
                if (users.size() > 0) {
                    String[] strings = new String[users.size()];
                    for (int i = 0; i < users.size(); i++) {
                        strings[i] = users.get(i).getUsername();
                    }
                    AlertDialog alertDialog = new AlertDialog
                            .Builder(getContext())
                            .setTitle("contact request list  点击验证好友")
                            .setItems(strings, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    CCIMClient.getInstance().checkContactReq(users.get(which).getUserId(), true, new ResultEventCallback<Void>() {
                                        @Override
                                        public void onSuccess(Void unused) {
                                            ToastUtil.show(getContext(), "验证好友发送成功");
                                            loginViewModel.getContactList();
                                        }

                                        @Override
                                        public void onFailed(int errorCode) {
                                            ToastUtil.show(getContext(), "验证好友失败 : " + errorCode);
                                        }
                                    });
                                }
                            })
                            .create();
                    alertDialog.show();
                }
            }

            @Override
            public void onFailed(int errorCode) {

            }
        });
    }


    public void showSearchResultdialog(List<User> users) {
        String[] strings = new String[users.size()];
        for (int i = 0; i < users.size(); i++) {
            strings[i] = users.get(i).getUsername();
        }
        AlertDialog alertDialog = new AlertDialog
                .Builder(getContext())
                .setTitle("userList  点击加好友")
                .setItems(strings, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        CCIMClient.getInstance().addContact(users.get(which).getUserId(), new ResultEventCallback<Void>() {
                            @Override
                            public void onSuccess(Void unused) {
                                ToastUtil.show(getContext(), "加好友发送成功");
                            }

                            @Override
                            public void onFailed(int errorCode) {
                                ToastUtil.show(getContext(), "加好友失败 : " + errorCode);
                            }
                        });
                    }
                })
                .setNegativeButton("关闭", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                })
                .create();
        alertDialog.show();
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
}