package cc.smtweb.framework.core.cache;

import cc.smtweb.framework.core.common.SwConsts;
import cc.smtweb.framework.core.db.DbEngine;
import cc.smtweb.framework.core.db.EntityDao;
import cc.smtweb.framework.core.db.impl.DefaultEntity;
import cc.smtweb.framework.core.util.CommUtil;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by Akmm at 2022/6/16 15:53
 */
public class AbstractEntityCache<T extends DefaultEntity> extends AbstractCache<T> {
    @Override
    protected String getId(T bean) {
        return String.valueOf(bean.getEntityId());
    }

    private String getCacheKey(T bean, String fields) {
        String[] fs = fields.split(",");
        String ret = "";
        for (String f : fs) {
            ret += SwConsts.SPLIT_CHAR + bean.getStr(f);
        }
        return ret.substring(SwConsts.SPLIT_CHAR.length());
    }

    /**
     * 注册其他key的List缓存，如tree的children
     *
     * @param key
     * @param fields
     */
    protected void regList(String key, String fields) {
        regList(key, bean -> getCacheKey(bean, fields));
    }

    /**
     * 注册其他key的Map缓存，如按code缓存
     *
     * @param key
     * @param fields
     */

    protected void regMap(String key, String fields) {
        regMap(key, bean -> getCacheKey(bean, fields));
    }

    @Override
    protected List<T> loadAll() {
        EntityDao<T> dao = DbEngine.getInstance().findDao(pTypeClass);
        return dao.query();
    }


    public final Set<Long> getListIdByKey(String rk, String key) {
        Set<Long> idSet = new HashSet<>();
        Set<T> beanSet = getListByKey(rk, key);
        if (CommUtil.isEmpty(beanSet)) return idSet;
        beanSet.forEach(bean -> {
            idSet.add(bean.getEntityId());
        });
        return idSet;
    }
}
