package com.pingpang.controller;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.pingpang.redis.RedisPre;
import com.pingpang.redis.service.RedisService;
import com.pingpang.service.UserService;
import com.pingpang.util.StringUtil;
import com.pingpang.websocketchat.ChartUser;


@RestController
@RequestMapping("/autho")
public class AuthoRtmp {
	
	@DubboReference
	private RedisService redisService;
	
    @DubboReference
	private UserService userService;
	
	Logger logger = LoggerFactory.getLogger(AuthoRtmp.class);
			
	@RequestMapping(value = "/rtmp", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public void autho(HttpServletRequest request, HttpServletResponse response) {
		String userCode=request.getParameter("name");
		String token=request.getParameter("token");
		logger.info("用户{},token码{}",userCode,token);
        if(StringUtil.isNUll(userCode)||StringUtil.isNUll(token)) {
        	response.setStatus(401);
            return;        	
        }else {
        	String tokenRedis=(String) redisService.get(RedisPre.AUDIO_LIVE_TOKEN+userCode);
        	if(!token.equals(tokenRedis)) {
        		logger.info("用户{},鉴权失败",userCode);
        		response.setStatus(401);
                return;  
        	}else {
        		
        		ChartUser liveUser=new ChartUser();
        		liveUser.setUserCode(userCode);
        		
        		ChartUser cu=this.userService.getUser(liveUser);
        		if(null==cu) {
                   logger.info("用户{}不存在"+userCode);
                   response.setStatus(401);
                   return;
        		}
        		
				cu.setUserStatus("");
				cu.setLiveType("1");
				this.redisService.addSet(RedisPre.AUDIO_LIVE_SET+userCode,cu);
        		
        		response.setStatus(200);
                return; 
        	}
        }
	}
	
	@RequestMapping(value = "/rtmpOver", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public void authoOver(HttpServletRequest request, HttpServletResponse response) {
		String userCode=request.getParameter("name");
		String token=request.getParameter("token");
		logger.info("用户{},token码{},鉴权移除",userCode,token);
        if(StringUtil.isNUll(userCode)||StringUtil.isNUll(token)) {
        	response.setStatus(401);
            return;        	
        }else {
        	String tokenRedis=(String) redisService.get(RedisPre.AUDIO_LIVE_TOKEN+userCode);
        	if(!token.equals(tokenRedis)) {
        		logger.info("用户{},鉴权移除失败",userCode);
        		response.setStatus(401);
                return;  
        	}else {
        		//移除token
        		redisService.delete(RedisPre.AUDIO_LIVE_TOKEN+userCode);
        		//删除直播间
        		redisService.delete(RedisPre.AUDIO_LIVE_SET+userCode);
        		response.setStatus(200);
                return; 
        	}
        }
	}
	
	@RequestMapping(value="/getToken",method=RequestMethod.POST)
 	@ResponseBody
 	public  Map<String,String> getToken(HttpServletRequest request) throws Exception {
	      Map<String,String> tokenResult=new HashMap<String,String>();
	      ChartUser usr=(ChartUser)request.getSession().getAttribute("user");
	      String tokenId=UUID.randomUUID().toString().replace("-", "");
	      redisService.set(RedisPre.AUDIO_LIVE_TOKEN+usr.getUserCode(),tokenId);
	      redisService.expireKey(RedisPre.AUDIO_LIVE_TOKEN+usr.getUserCode(), 60*2);
	      tokenResult.put("token", usr.getUserCode()+"?token="+tokenId);
	      return tokenResult;
	}
	
	/**
	 * flv.js直播
	 * @return
	 */
	@CrossOrigin(origins = "*")
	@RequestMapping("/videoLiveRtm")
	public ModelAndView rtmLiveConsole(HttpServletRequest request) {
		request.setAttribute("liveCode", request.getParameter("liveCode"));
		return new ModelAndView("videoLiveRtm");
	}
}
