package com.guwan.face.util;

import com.google.common.collect.Lists;

import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

public class UserRamCache {

    private final ConcurrentHashMap<String, UserInfo> USER_INFO_MAP = new ConcurrentHashMap<>();

    private final Set<Listener> REGISTER = new CopyOnWriteArraySet<>();

    public void addUser(UserInfo userInfo) {
        USER_INFO_MAP.put(userInfo.getFaceId(), userInfo);
        for (Listener listener : REGISTER) {
            listener.onAdd(userInfo);
        }
    }

    public void removeUser(String faceId) {
        UserInfo userInfo = USER_INFO_MAP.remove(faceId);
        for (Listener listener : REGISTER) {
            listener.onRemove(userInfo);
        }
    }

    public List<UserInfo> getUserList() {
        List<UserInfo> userInfoList = Lists.newLinkedList();
        userInfoList.addAll(USER_INFO_MAP.values());
        return userInfoList;
    }

    public void clear(){
        USER_INFO_MAP.clear();
        REGISTER.clear();
    }

    public void addListener(Listener listener) {
        REGISTER.add(listener);
    }

    public void removeListener(Listener listener) {
        REGISTER.remove(listener);
    }

//    @Data
//    public class UserInfo {
//
//        private String faceId;
//        private String name;
//        private byte[] faceFeature;
//
//    }

    public interface Listener {
        default void onAdd(UserInfo userInfo) {
        }

        default void onRemove(UserInfo userInfo) {

        }
    }
}
