package ink.wgink.gateway.component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import ink.wgink.gateway.dao.route.IRouteDao;
import ink.wgink.gateway.pojo.route.Route;
import ink.wgink.gateway.util.DateUtil;
import ink.wgink.gateway.util.RegexUtil;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.cloud.gateway.event.RefreshRoutesEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

/**
 * @ClassName: ApiPublishConsumer
 * @Description: api发布消费者
 * @Author: wanggeng
 * @Date: 2021/8/22 9:31 下午
 * @Version: 1.0
 */
@Component
public class ApiPublishConsumer implements ApplicationEventPublisherAware {

    private ApplicationEventPublisher applicationEventPublisher;
    private MongoTemplate mongoTemplate;

    public ApiPublishConsumer(MongoTemplate mongoTemplate) {
        this.mongoTemplate = mongoTemplate;
    }

    @KafkaListener(topics = {"apiPublish"})
    public void onPublish(ConsumerRecord<?, ?> record) {
        JSONObject publishObject = JSON.parseObject(record.value().toString());
        JSONObject apiObject = publishObject.getJSONObject("api");
        JSONObject systemObject = publishObject.getJSONObject("system");
        System.out.println(apiObject);
        Route route = new Route();
        route.setUuid(apiObject.getString("apiId"));
        route.setTitle(apiObject.getString("title"));
        route.setUri(String.format("%s://%s", systemObject.getString("requestSchema"), systemObject.getString("ipAddress")));
        route.setPath(String.format("%s%s", systemObject.getString("systemContext"), RegexUtil.replacePathParams(apiObject.getString("url"), "*")));

        String datetime = DateUtil.getTime();
        route.setCreator("1");
        route.setGmtCreate(datetime);
        route.setModifier("1");
        route.setGmtModified(datetime);

        mongoTemplate.save(route, IRouteDao.COLLECTION_NAME);
        this.applicationEventPublisher.publishEvent(new RefreshRoutesEvent(this));

    }

    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        this.applicationEventPublisher = applicationEventPublisher;
    }
}
