package com.qiuguo.iot.box.websocket.api.service;

import com.alibaba.fastjson.JSONObject;
import com.qiuguo.iot.box.websocket.api.domain.BaseSession;
import com.qiuguo.iot.box.websocket.api.domain.box.resp.BoxMessageResp;
import com.qiuguo.iot.box.websocket.api.handler.BoxWebSocketHandler;
import com.qiuguo.iot.box.websocket.api.handler.CustomerWebSocketHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;

@Service
@Slf4j
public class WebsocketService {
    @Autowired
    BoxWebSocketHandler boxWebSocketHandler;
    @Autowired
    CustomerWebSocketHandler customerWebSocketHandler;


    public Mono<String> pushMessage(String message, String id, Integer type) {

        if(type == 0){
            //设备推送
            BaseSession boxSession = boxWebSocketHandler.getBoxSessionWithSn(id);
            if(boxSession != null){

                BoxMessageResp resp = new BoxMessageResp();
                resp.setType(0);
                resp.setText(message);
                boxSession.getSink().next(boxSession.getSession().textMessage(JSONObject.toJSONString(resp)));
                return Mono.just("推送成功");
            }
            return Mono.just("设备未上线");
        }else{
            //用户推送
            BaseSession userSession = customerWebSocketHandler.getUserSessionWithUserId(Long.parseLong(id));
            if(userSession != null){
                BoxMessageResp resp = new BoxMessageResp();
                resp.setType(0);
                resp.setText(message);
                userSession.getSink().next(userSession.getSession().textMessage(JSONObject.toJSONString(resp)));
                return Mono.just("推送成功");
            }
            return Mono.just("用户未上线");
        }
    }
}
