package cn.reghao.tnb.gateway.admin;

import cn.reghao.tnb.gateway.admin.handler.DynamicRouteHandler;
import cn.reghao.tnb.gateway.admin.handler.ServiceRouteHandler;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.HttpHandler;
import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter;
import org.springframework.stereotype.Component;
import reactor.netty.http.server.HttpServer;

import static org.springframework.web.reactive.function.server.RequestPredicates.*;
import static org.springframework.web.reactive.function.server.RouterFunctions.route;
import static org.springframework.web.reactive.function.server.RouterFunctions.toHttpHandler;

import jakarta.annotation.PostConstruct;

/**
 * @author reghao
 * @date 2024-11-21 11:18:10
 */
@Component
public class AdminServer {
    private final DynamicRouteHandler dynamicRouteHandler;
    private final ServiceRouteHandler serviceRouteHandler;

    public AdminServer(DynamicRouteHandler dynamicRouteHandler, ServiceRouteHandler serviceRouteHandler) {
        this.dynamicRouteHandler = dynamicRouteHandler;
        this.serviceRouteHandler = serviceRouteHandler;
    }

    @PostConstruct
    public void start() {
        HttpHandler httpHandler = toHttpHandler(
                route(POST("/route").and(accept(MediaType.APPLICATION_JSON_UTF8)), dynamicRouteHandler::add)
                        .and(route(POST("/route/update"), dynamicRouteHandler::update))
                        .and(route(POST("/route/delete"), dynamicRouteHandler::delete))
                        .and(route(GET("/routes"), dynamicRouteHandler::getAllRoutes))
                        .and(route(GET("/route"), dynamicRouteHandler::getRoute))
                        .and(route(GET("/route/redis"), dynamicRouteHandler::getRoutes))
                        .and(route(GET("/service"), serviceRouteHandler::getAllServices))
        );
        ReactorHttpHandlerAdapter httpHandlerAdapter = new ReactorHttpHandlerAdapter(httpHandler);
        HttpServer.create().host("0.0.0.0").port(16000).handle(httpHandlerAdapter).bindNow();
    }
}
