package com.ym.mec.teacher.controller;

import com.alibaba.fastjson.JSON;
import com.ym.mec.biz.dal.dto.MusicPitchDetailDto;
import com.ym.mec.biz.service.SoundService;
import com.ym.mec.common.controller.BaseController;
import com.ym.mec.common.entity.HttpResponseResult;
import com.ym.mec.biz.handler.WebSocketHandler;
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("sound")
@RestController
public class SoundController extends BaseController {

    private final Logger LOGGER = LoggerFactory.getLogger(SoundController.class);

    @Autowired
    private SoundService soundService;

    @ApiOperation(value = "评分")
    @PostMapping("compare")
    public HttpResponseResult compare(@RequestParam("record") MultipartFile record, Integer musicScoreId){
        return soundService.compare(record, musicScoreId);
    }

    @ApiOperation(value = "小节评分")
    @PostMapping("measureCompare")
    public HttpResponseResult measureCompare(@RequestParam("musicXmlInfos") String musicXmlInfos,@RequestParam("record") MultipartFile record){
        if(StringUtils.isBlank(musicXmlInfos)){
            return failed();
        }
        List<MusicPitchDetailDto> musicXmlInfoList =  JSON.parseArray(musicXmlInfos, MusicPitchDetailDto.class);
        return soundService.measureCompare(musicXmlInfoList, record);
    }

    @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).isOpen()){
            return failed("已离线");
        }
        WebSocketHandler.WS_CLIENTS.get(phone).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).isOpen()){
            return failed("已离线");
        }
        WebSocketHandler.WS_CLIENTS.get(phone).close();
        return succeed();
    }

}
