package chat;

import com.ruoyi.common.core.domain.AjaxResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.messaging.converter.MappingJackson2MessageConverter;
import org.springframework.messaging.simp.stomp.StompSession;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.socket.WebSocketHttpHeaders;
import org.springframework.web.socket.client.standard.StandardWebSocketClient;
import org.springframework.web.socket.messaging.WebSocketStompClient;

import javax.annotation.PostConstruct;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/client")
public class GreetingIntegrationController {

    @Value("${url:ws://localhost:8080/gs-guide-websocket}")
    private String url;

    private StompSession stompSession;

    @PostConstruct
    public void GreetingIntegration() {
        WebSocketStompClient stompClient = new WebSocketStompClient(new StandardWebSocketClient());
        stompClient.setMessageConverter(new MappingJackson2MessageConverter());
        ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
        taskScheduler.initialize();
        ListenableFuture<StompSession> connect = stompClient.connect(url, new WebSocketHttpHeaders(), new MyStompSessionHandler());
        try {
            stompSession = connect.get();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @PostMapping("/message")
    private AjaxResult getMessage(@RequestBody String message) {
        if (message == null || "".equals(message))
            return AjaxResult.error("请求内容为空！");

        MediatorService.countDownLatch = new CountDownLatch(1);
        stompSession.send("/app/hello", new HelloMessage(message));
        try {
            if (MediatorService.countDownLatch.await(3, TimeUnit.MINUTES)) {
                return AjaxResult.success(MediatorService.greeting);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return AjaxResult.error("请求失败！");
    }
}
