package cn.stylefeng.team.generator.sdk.template;

import cn.hutool.core.io.resource.ResourceUtil;
import cn.stylefeng.roses.kernel.cache.api.CacheOperatorApi;
import cn.stylefeng.team.generator.api.TemplateGetApi;
import cn.stylefeng.team.generator.api.enums.GeneratorTypeEnum;
import cn.stylefeng.team.generator.api.pojo.template.BizGeneratorTemplateGroup;
import cn.stylefeng.team.generator.api.pojo.template.GeneratorTemplateGroup;
import cn.stylefeng.team.generator.sdk.template.factory.BizTemplateFactory;
import cn.stylefeng.team.generator.sdk.template.factory.TemplateFactory;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

@Service
public class TemplateServiceImpl implements TemplateGetApi {

    @Resource(name = "generatorTemplateGroupCache")
    private CacheOperatorApi<GeneratorTemplateGroup> generatorTemplateGroupCache;

    @Resource(name = "bizGeneratorTemplateGroupCache")
    private CacheOperatorApi<BizGeneratorTemplateGroup> bizGeneratorTemplateGroupCache;

    @Override
    public GeneratorTemplateGroup getTemplateGroup(GeneratorTypeEnum generatorTypeEnum) {

        GeneratorTemplateGroup generatorTemplateGroup = generatorTemplateGroupCache.get(generatorTypeEnum.getCode().toString());

        if (generatorTemplateGroup != null) {
            return generatorTemplateGroup;
        }

        generatorTemplateGroup = TemplateFactory.proxyCreateTemplate(generatorTypeEnum);

        generatorTemplateGroupCache.put(generatorTypeEnum.getCode().toString(), generatorTemplateGroup);

        return generatorTemplateGroup;
    }

    @Override
    public String getTemplateContentByResourceId(String resourceId) {
        return ResourceUtil.readUtf8Str(resourceId);
    }

    @Override
    public BizGeneratorTemplateGroup getBizBackendTemplateGroup() {

        String cacheKey = GeneratorTypeEnum.BIZ_BACKEND_GENERATE.getCode().toString();

        BizGeneratorTemplateGroup bizGeneratorTemplateGroup = bizGeneratorTemplateGroupCache.get(cacheKey);

        if (bizGeneratorTemplateGroup != null) {
            return bizGeneratorTemplateGroup;
        }

        bizGeneratorTemplateGroup = BizTemplateFactory.createBizGenerateTemplateGroup();

        bizGeneratorTemplateGroupCache.put(cacheKey, bizGeneratorTemplateGroup);

        return bizGeneratorTemplateGroup;
    }

}
