package com.ccwangluo.im.ui.notifications;

import android.app.AlertDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.InputType;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
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.AudioRoomListener;
import com.ccwangluo.ccim.listener.ResultEventCallback;
import com.ccwangluo.im.adapter.ChannelAdapter;
import com.ccwangluo.im.data.LoginViewModel;
import com.ccwangluo.im.databinding.FragmentNotificationsBinding;
import com.ccwangluo.im.listener.ChannelClickListener;
import com.ccwangluo.im.ui.login.TestActivity;
import com.ccwangluo.im.util.ToastUtil;

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

public class NotificationsFragment extends Fragment {

    private LoginViewModel loginViewModel;
    private FragmentNotificationsBinding binding;
    private List<Long> list = new ArrayList<>();
    private ChannelAdapter channelAdapter;
    private NavController navController;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        loginViewModel =
                new ViewModelProvider(getActivity()).get(LoginViewModel.class);

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

        channelAdapter = new ChannelAdapter(list, getContext(), new ChannelClickListener() {
            @Override
            public void itemClick(Long id) {
//                Bundle bundle = new Bundle();
//                bundle.putLong("channelId", id);
//                navController.navigate(R.id.navigation_channel_connect, bundle);
                Intent intent = new Intent(getContext(), ConnectChannelActivity.class);
                intent.putExtra("channelId", id);
                startActivity(intent);
            }

            @Override
            public void itemLongClick(Long id) {
                longItemClick(id);
            }
        });

        binding.channelList.setAdapter(channelAdapter);

        loginViewModel.channelList.observe(getViewLifecycleOwner(), new Observer<List<Long>>() {
            @Override
            public void onChanged(List<Long> longs) {
                list.clear();
                list.addAll(longs);
                channelAdapter.notifyDataSetChanged();
            }
        });

        binding.joinChannel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final EditText inputServer = new EditText(getContext());
                inputServer.requestFocus();
                AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
                builder.setTitle("channel id").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 channelId = inputServer.getText().toString();
                        if (TextUtils.isEmpty(channelId)) {
                            ToastUtil.show(getContext(), "channel id is null");
                            return;
                        }
                        long Id = Long.parseLong(channelId);
                        CCIMClient.getInstance().joinChannel(Id, new ResultEventCallback<Void>() {
                            @Override
                            public void onSuccess(Void unused) {
                                ToastUtil.show(getContext(), "join success");
                                loginViewModel.addChannelId(Id);
                            }

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

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

        binding.createChannel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final EditText channelName = new EditText(getContext());
                channelName.setHint("channel name");
                final EditText tagView = new EditText(getContext());
                tagView.setHint("tag");
                CheckBox checkBox = new CheckBox(getContext());
                final EditText userList = new EditText(getContext());
                userList.setHint("好友");
                LinearLayout linearLayout = new LinearLayout(getContext());
                linearLayout.setOrientation(LinearLayout.VERTICAL);
                linearLayout.addView(channelName);
                linearLayout.addView(tagView);
                linearLayout.addView(checkBox);
                linearLayout.addView(userList);
                AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
                builder.setTitle("create channel").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 name = channelName.getText().toString();
                        String tag = tagView.getText().toString();
                        boolean checked = checkBox.isChecked();
                        String users = userList.getText().toString();
                        ArrayList<Long> longs = new ArrayList<>();
                        if (!TextUtils.isEmpty(users)) {
                            String[] split = users.split(",");
                            for (int i = 0; i < split.length; i++) {
                                longs.add(Long.parseLong(split[i]));
                            }
                        }
                        CCIMClient.getInstance().createChannel(name, tag, checked, longs, new ResultEventCallback<Long>() {
                            @Override
                            public void onSuccess(Long aLong) {
                                //获取剪贴板管理器：
                                loginViewModel.addChannelId(aLong);
                                if (getContext() != null) {
                                    ClipboardManager cm = (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);
                                    ClipData mClipData = ClipData.newPlainText("Label", aLong.toString());
                                    cm.setPrimaryClip(mClipData);
                                    ToastUtil.show(getContext(), "create success,id copy success");
                                }
                            }

                            @Override
                            public void onFailed(int errorCode) {
                                ToastUtil.show(getContext(), " onFailed  :" + errorCode);
                            }
                        });
                    }
                });
                builder.show();
            }
        });
        binding.joinRoom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final EditText roomeId = new EditText(getContext());
                roomeId.setHint("room id");
                roomeId.setInputType(InputType.TYPE_CLASS_NUMBER);
                roomeId.requestFocus();
                LinearLayout linearLayout = new LinearLayout(getContext());
                linearLayout.setOrientation(LinearLayout.VERTICAL);
                linearLayout.addView(roomeId);
                AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
                builder.setTitle("create channel").setIcon(android.R.drawable.ic_dialog_info).setView(linearLayout)
                        .setNegativeButton("Cancel", null);
                builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String roomId = roomeId.getText().toString();
                        CCIMClient.getInstance().joinAudioRoom(getContext(), Integer.parseInt(roomId), new AudioRoomListener() {
                            @Override
                            public void onJoinSuccess() {
                                ToastUtil.show(getContext(), "onJoinSuccess");
                            }

                            @Override
                            public void onJoinFailed(int code) {
                                ToastUtil.show(getContext(), "onJoinFailed" + code);
                            }

                            @Override
                            public void onExit() {
                                ToastUtil.show(getContext(), "onExit");
                            }

                            @Override
                            public void onError(int code) {
                                ToastUtil.show(getContext(), "onError");
                            }
                        });
                    }
                });
                builder.show();

            }
        });

        binding.disableAudio.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CCIMClient.getInstance().setLocalAudio(false);
            }
        });
        binding.enableAudio.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CCIMClient.getInstance().setLocalAudio(true);
            }
        });
        binding.exitRoom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CCIMClient.getInstance().exitAudioRoom();
            }
        });
        return root;
    }

    private void longItemClick(Long id) {
        String[] strings = {"退出频道"};
        AlertDialog alertDialog = new AlertDialog
                .Builder(getContext())
                .setItems(strings, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which) {
                            case 0:
                                CCIMClient.getInstance().exitChannel(id, new ResultEventCallback<Void>() {
                                    @Override
                                    public void onSuccess(Void unused) {
                                        loginViewModel.removeChannelId(id);
                                        ToastUtil.show(getContext(), "退出成功");
                                    }

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

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

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

}