package com.ym.im.handler;

import com.ym.im.entity.DeviceTokenParam;
import com.ym.im.entity.StaffSocketInfo;
import com.ym.im.entity.UserSocketInfo;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author: JJww
 * @Date:2020/10/14
 */
@Component
public class ChannelGroupHandler {

    /**
     * 在线用户Group
     */
    public final Map<Long, UserSocketInfo> USER_GROUP = new ConcurrentHashMap<>();

    /**
     * 在线客服Group
     */
    public final Map<Long, Map<Long, StaffSocketInfo>> STAFF_GROUP = new ConcurrentHashMap<>();

    /**
     * 用户推送tokenGroup
     */
    public final Map<Long, DeviceTokenParam> USER_DEVICE_PUSH_TOKEN = new ConcurrentHashMap<>();


    /**
     * 新增商户 客服
     *
     * @param merchantId
     * @param staffSocketInfo
     */
    public void putMerchantStaff(Long merchantId, StaffSocketInfo staffSocketInfo) {
        final Map<Long, StaffSocketInfo> staffSocketInfoMap = STAFF_GROUP.get(merchantId) != null ? STAFF_GROUP.get(merchantId) : new HashMap<Long, StaffSocketInfo>();
        staffSocketInfoMap.put(staffSocketInfo.getStaffId(), staffSocketInfo);
        STAFF_GROUP.put(merchantId, staffSocketInfoMap);
    }

    /**
     * 移除商户 客服
     *
     * @param merchantId
     * @param staffId
     */
    public void removeMerchantStaff(Long staffId) {
        StaffSocketInfo staffSocketInfo = null;
        for (Map<Long, StaffSocketInfo> staffGroup : STAFF_GROUP.values()) {
            StaffSocketInfo staffInfo = staffGroup.get(staffId);
            if (staffInfo != null) {
                staffGroup.remove(staffId);
                break;
            }
        }
    }


    public StaffSocketInfo getMerchantStaff(Long merchantId, Long staffId) {
        return STAFF_GROUP.get(merchantId) != null ? STAFF_GROUP.get(merchantId).get(staffId) : null;
    }

    public StaffSocketInfo getMerchantStaff(Long staffId) {
        StaffSocketInfo staffSocketInfo = null;
        for (Map<Long, StaffSocketInfo> staffGroup : STAFF_GROUP.values()) {
            StaffSocketInfo staffInfo = staffGroup.get(staffId);
            if (staffInfo != null) {
                staffSocketInfo = staffInfo;
                break;
            }
        }
        return staffSocketInfo;
    }
}