package cc.smtweb.framework.core.db.cache;

import cc.smtweb.framework.core.cache.AbstractCache;
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.db.vo.ModelCache;
import cc.smtweb.framework.core.db.vo.ModelTable;
import cc.smtweb.framework.core.mvc.controller.scan.BeanManager;
import cc.smtweb.framework.core.util.CommUtil;
import org.apache.commons.lang3.StringUtils;

import java.util.List;

/**
 * Created by Akmm at 2022/2/19 17:19
 */
public class EntityCache extends AbstractCache<DefaultEntity> {
    private String tableName;

    public EntityCache(String tableName) {
        this.tableName = tableName;
        Class<DefaultEntity> clazz = (Class<DefaultEntity>) BeanManager.getInstance().getTableClass(tableName);
        if (clazz != null) {
            this.pTypeClass = clazz;
        }

        ModelTable table = ModelTableCache.getInstance().getByName(tableName);

        ident = tableName;
        title = table.getTitle();
        lazy = false;

        if (!table.isNeedCache() || CommUtil.isEmpty(table.getCaches())) return;

        for (ModelCache cache : table.getCaches()) {
            final IGetBeanKey<DefaultEntity> key = bean -> {
                String ret = "";
                for (String s : StringUtils.split(cache.getFields(), ",")) {
                    if (StringUtils.isNotEmpty(s)) {
                        ret += SwConsts.SPLIT_CHAR + bean.getStr(s);
                    }
                }
                return ret.substring(1);
            };
            if (cache.isMapType()) {
                regMap(cache.getName(), key);
            } else {
                regList(cache.getName(), key);
            }
        }
    }

    @Override
    protected String getId(DefaultEntity bean) {
        return String.valueOf(bean.getEntityId());
    }

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

}
