package cn.ey.biz.module.system.framework.dynamic_api.core.service;

import cn.ey.biz.module.system.framework.dynamic_api.core.AbstractResourceStorage;
import cn.ey.biz.module.system.framework.dynamic_api.core.model.ApiInfo;
import lombok.Data;

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

import static cn.ey.biz.common.exception.util.ServiceExceptionUtil.exception;

public abstract class AbstractDynamicRegistry implements IDynamicRegistry {

	/**
	 * 已缓存的映射信息
	 */
	private final Map<String, MappingNode> mappings = new ConcurrentHashMap<>();

	protected final AbstractResourceStorage resourceStorage;

	public AbstractDynamicRegistry(AbstractResourceStorage resourceStorage) {
		this.resourceStorage = resourceStorage;
	}

	@Override
	public boolean register(ApiInfo entity) {
		MappingNode mappingNode = buildMappingNode(entity);
		String mppingKey = mappingNode.getMappingKey();
		if (mappings.containsKey(mppingKey)) {
			throw exception(-1, mppingKey + " 已注册，请更换名称或路径");
		}
		if (register(mappingNode)) {
			mappings.put(mppingKey, mappingNode);
			return true;
		}
		return false;
	}

	@Override
	public boolean unregister(ApiInfo entity) {
		MappingNode mappingNode = mappings.remove(entity.getId());
		if (mappingNode != null) {
			mappings.remove(mappingNode.getMappingKey());
			unregister(mappingNode);
			return true;
		}
		return false;
	}

	protected boolean register(MappingNode mappingNode) {
		return true;
	}

	protected void unregister(MappingNode mappingNode) {}

	protected MappingNode buildMappingNode(ApiInfo entity) {
		MappingNode mappingNode = new MappingNode(entity);
		mappingNode.setMappingKey(this.resourceStorage.buildKey(entity));
		return mappingNode;
	}

	@Data
	protected static class MappingNode {
		private ApiInfo entity;
		private String mappingKey;
		private Object mappingData;
		public MappingNode(ApiInfo entity) {
			this.entity = entity;
		}
	}

}
