package cn.fateverse.query.dubbo;

import cn.fateverse.query.constant.QueryConstant;
import cn.fateverse.query.entity.bo.PortalBo;
import cn.fateverse.query.portal.service.HandlerMethodService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;

/**
 * @author Clay
 * @date 2024/4/19 11:02
 */
@Slf4j
@DubboService(scope = "remote")
public class DubboDispatchServletPublishImpl implements DubboDispatchServletPublish {


    @Resource
    private HandlerMethodService methodService;


    @Resource
    private RedisTemplate<String, PortalBo> redisTemplate;

    @Override
    public Boolean publish(String path, String requestMethod) {
        PortalBo portalBo = redisTemplate.opsForValue().get(QueryConstant.PORTAL_KEY + path + ":" + requestMethod);
        if (portalBo == null) {
            return Boolean.FALSE;
        }
        try {
            log.info("registerMapping, path:{}, requestMethod:{}", path, requestMethod);
            methodService.registerMapping(path, RequestMethod.valueOf(requestMethod), Boolean.FALSE);
        } catch (Exception e) {
            return Boolean.FALSE;
        }
        return Boolean.TRUE;
    }


    @Override
    public Boolean unpublish(String path, String requestMethod) {
        try {
            log.info("unregisterMapping, path:{}, requestMethod:{}", path, requestMethod);
            methodService.unregisterMapping(path, RequestMethod.valueOf(requestMethod), Boolean.FALSE);
        } catch (Exception e) {
            return Boolean.FALSE;
        }
        return Boolean.TRUE;
    }
}
