package com.rong.io.live.widget;

import android.content.Context;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.cooleshow.usercenter.helper.UserHelper;
import com.rong.io.live.R;

import java.util.ArrayList;

import androidx.annotation.Nullable;
import io.rong.imlib.model.UserInfo;

/**
 * Author by pq, Date on 2022/4/6.
 */
public class LiveRoomMicIconView extends LinearLayout {
    private ArrayList<UserInfo> mMicUserInfos;
    private String mCurrentUserId;
    public static final String DEFAULT_NICK = "连麦用户";
    public OnEventListener mEventListener;
    private String mCurrentUserName;

    public LiveRoomMicIconView(Context context) {
        this(context, null);
    }

    public LiveRoomMicIconView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, -1);
    }

    public LiveRoomMicIconView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        setOrientation(HORIZONTAL);
        setGravity(Gravity.CENTER_VERTICAL);
        mMicUserInfos = new ArrayList<>();
        mCurrentUserId = UserHelper.getUserId();
        mCurrentUserName = UserHelper.getUserName();
    }

    public void delAll() {
        if (mMicUserInfos != null) {
            mMicUserInfos.clear();
            this.removeAllViews();
        }
    }

    private void refreshAllUser() {
        removeAllViews();
        createMicTag();
    }

    public void updateTargetUserInfo(UserInfo userInfo) {
        int i = checkContain(userInfo.getUserId());
        if (i != -1) {
            String oldName = mMicUserInfos.get(i).getName();
            if (!TextUtils.isEmpty(oldName) && !TextUtils.equals(oldName, DEFAULT_NICK)) {
                userInfo.setName(mMicUserInfos.get(i).getName());
            }
            mMicUserInfos.set(i, userInfo);
        } else {
            mMicUserInfos.add(userInfo);
        }
        refreshAllUser();
    }

    private void createMicTag() {
        for (int i = 0; i < mMicUserInfos.size(); i++) {
            UserInfo userInfo = mMicUserInfos.get(i);
            View view = LayoutInflater.from(getContext()).inflate(R.layout.item_live_room_mic_user_layout, this, false);
            ImageView iv_icon = view.findViewById(R.id.iv_icon);
            TextView tv_name = view.findViewById(R.id.tv_name);
            String nickName = DEFAULT_NICK;
            if (!TextUtils.isEmpty(userInfo.getName())) {
                nickName = userInfo.getName();
            }
            userInfo.setName(nickName);
            tv_name.setText(nickName);
            if (userInfo != null && TextUtils.equals(userInfo.getUserId(), mCurrentUserId)) {
                //自己
                iv_icon.setImageResource(R.drawable.icon_live_room_mic_own);
                tv_name.setBackgroundResource(R.drawable.shape_live_room_mic_nickname_bg);
            } else {
                iv_icon.setImageResource(R.drawable.icon_live_room_mic_other);
                tv_name.setBackgroundResource(R.drawable.shape_live_room_mic_nickname_bg_normal);
            }
            this.addView(view);
        }
    }

    public void deleteMicUser(UserInfo userInfo) {
        int i = checkContain(userInfo.getUserId());
        if (i != -1) {
            try {
                mMicUserInfos.remove(i);
                this.removeViewAt(i);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

    private int checkContain(String id) {
        int pos = -1;

        if (mMicUserInfos.size() == 0) {
            return pos;
        }
        for (int i = 0; i < mMicUserInfos.size(); i++) {
            UserInfo targetUserInfo = mMicUserInfos.get(i);
            if (TextUtils.equals(id, targetUserInfo.getUserId())) {
                pos = i;
                return pos;
            }
        }
        return pos;
    }

    public void refreshUI(ArrayList<String> onMicUserIds) {
        post(new Runnable() {
            @Override
            public void run() {
                if (onMicUserIds != null && onMicUserIds.size() > 0) {
                    ArrayList<UserInfo> lastOnMicUser = new ArrayList<>();
                    if (mMicUserInfos != null && mMicUserInfos.size() != 0) {
                        for (int i = 0; i < mMicUserInfos.size(); i++) {
                            //找出已有的连麦用户信息
                            UserInfo userInfo = mMicUserInfos.get(i);
                            int pos = checkExitForTargetList(userInfo.getUserId(), onMicUserIds);
                            if (pos != -1) {
                                lastOnMicUser.add(userInfo);
                                onMicUserIds.remove(pos);
                            }
                        }
                    }
                    for (int i = 0; i < onMicUserIds.size(); i++) {
                        String s = onMicUserIds.get(i);
                        UserInfo userInfo = new UserInfo(s, DEFAULT_NICK, null);
                        lastOnMicUser.add(userInfo);
                    }
                    delAll();
                    for (int i = 0; i < lastOnMicUser.size(); i++) {
                        UserInfo targetUser = lastOnMicUser.get(i);
                        if (TextUtils.equals(targetUser.getUserId(), mCurrentUserId)) {
                            //如果是自身则不需要查询,直接取缓存名称
                            targetUser.setName(mCurrentUserName);
                        }
                        String lastName = targetUser.getName();
                        if (TextUtils.isEmpty(lastName) || TextUtils.equals(lastName, DEFAULT_NICK)) {
                            //如果昵称为空,查询昵称
                            if (mEventListener != null) {
                                mEventListener.getUserInfoByUserId(targetUser.getUserId());
                            }
                        }
                    }
                    mMicUserInfos.addAll(lastOnMicUser);
                    refreshAllUser();
                } else {
                    delAll();
                }
            }
        });
    }

    private int checkExitForTargetList(String targetUserId, ArrayList<String> targetList) {
        if (targetList == null || TextUtils.isEmpty(targetUserId)) {
            return -1;
        }
        for (int i = 0; i < targetList.size(); i++) {
            String s = targetList.get(i);
            if (TextUtils.equals(targetUserId, s)) {
                return i;
            }
        }
        return -1;
    }

    public void setOnEventListener(OnEventListener listener) {
        mEventListener = listener;
    }

    public interface OnEventListener {
        void getUserInfoByUserId(String userId);
    }
}
