package com.ym.mec.web.controller;

import com.alibaba.fastjson.JSON;
import com.ym.mec.biz.dal.dto.MusicPitchDetailDto;
import com.ym.mec.biz.handler.WebSocketHandler;
import com.ym.mec.biz.service.SoundService;
import com.ym.mec.common.controller.BaseController;
import com.ym.mec.common.entity.HttpResponseResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.socket.TextMessage;

import java.io.IOException;
import java.util.List;

/**
 * @Author Joburgess
 * @Date 2021/5/19 0019
 */
@Api(tags = "音频服务")
@RequestMapping("ws")
@RestController
public class WebsocketController extends BaseController {

    @ApiOperation(value = "获取在线人数")
    @GetMapping("getOnlineUserNum")
    public HttpResponseResult getOnlineUserNum(){
        return succeed(WebSocketHandler.WS_CLIENTS.keySet());
    }

    @RequestMapping("sendToUser")
    public HttpResponseResult sendToUser(String phone, String message) throws IOException {
        if(!WebSocketHandler.WS_CLIENTS.containsKey(phone)){
            return failed("未上线");
        }
        if(!WebSocketHandler.WS_CLIENTS.get(phone).getSession().isOpen()){
            return failed("已离线");
        }
        WebSocketHandler.WS_CLIENTS.get(phone).getSession().sendMessage(new TextMessage(message));
        return succeed();
    }

    @RequestMapping("closeWebSocket")
    public HttpResponseResult closeWebSocket(String phone) throws IOException {
        if(!WebSocketHandler.WS_CLIENTS.containsKey(phone)){
            return failed("未上线");
        }
        if(!WebSocketHandler.WS_CLIENTS.get(phone).getSession().isOpen()){
            return failed("已离线");
        }
        WebSocketHandler.WS_CLIENTS.get(phone).getSession().close();
        return succeed();
    }

}
