package com.qmth.themis.exam.websocket.interceptor;

import com.qmth.themis.business.constant.SystemConstant;
import com.qmth.themis.business.entity.TBSession;
import com.qmth.themis.business.enums.MonitorVideoSourceEnum;
import com.qmth.themis.business.util.AuthUtil;
import com.qmth.themis.common.contanst.Constants;
import com.qmth.themis.common.enums.ExceptionResultEnum;
import com.qmth.themis.common.enums.Platform;
import com.qmth.themis.common.exception.BusinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @Description: websocket移动端
 * @Param:
 * @return:
 * @Author: wangliang
 * @Date: 2020/7/10
 */
public class WebSocketMobileHandshakeInterceptor extends ServerEndpointConfig.Configurator {
    private final static Logger log = LoggerFactory.getLogger(WebSocketMobileHandshakeInterceptor.class);

    @Override
    public void modifyHandshake(ServerEndpointConfig config, HandshakeRequest request, HandshakeResponse response) {
        Map<String, List<String>> mapParameter = request.getParameterMap();
        if (Objects.isNull(mapParameter.get(Constants.HEADER_PLATFORM)) || mapParameter.get(Constants.HEADER_PLATFORM).size() == 0) {
            throw new BusinessException(ExceptionResultEnum.PLATFORM_INVALID);
        }
        Platform platform = Platform.valueOf(mapParameter.get(Constants.HEADER_PLATFORM).get(0));
        if (Objects.isNull(mapParameter.get(Constants.HEADER_DEVICE_ID)) || mapParameter.get(Constants.HEADER_DEVICE_ID).size() == 0) {
            throw new BusinessException(ExceptionResultEnum.DEVICE_ID_INVALID);
        }
        String deviceId = mapParameter.get(Constants.HEADER_DEVICE_ID).get(0);
        String authorization = mapParameter.get(Constants.HEADER_AUTHORIZATION).get(0);
        Long time = Long.parseLong(mapParameter.get(Constants.HEADER_TIME).get(0));
        Long recordId = Long.parseLong(mapParameter.get(Constants.HEADER_RECORD_ID).get(0));
        MonitorVideoSourceEnum source = MonitorVideoSourceEnum.valueOf(mapParameter.get(Constants.HEADER_SOURCE).get(0));

        TBSession tbSession = AuthUtil.websocketAuthInterceptor(platform, deviceId, authorization, time, SystemConstant.GET, SystemConstant.WEBSOCKET_MOBILE_PREFIX);
        SystemConstant.checkExamStatus(recordId);
        config.getUserProperties().put(Constants.HEADER_RECORD_ID, recordId);
        config.getUserProperties().put(Constants.HEADER_DEVICE_ID, deviceId);
        config.getUserProperties().put(Constants.HEADER_TB_SESSION, tbSession);
        config.getUserProperties().put(Constants.HEADER_SOURCE, source);
    }
}