package im.zhaojun.system.controller;

import im.zhaojun.common.util.PageResultBean;
import im.zhaojun.common.util.ResultBean;
import im.zhaojun.common.util.ThreadPoolUtil;
import im.zhaojun.system.model.UserOnline;
import im.zhaojun.system.service.UserOnlineService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.*;

@Controller
@RequestMapping("/online")
@Slf4j
public class UserOnlineController {
    @Value("${ipstrs}")
    String ipstrs;

    @Value("${ipurl}")
    String ipurl;

    @Autowired
    private RestTemplate restTemplate;

    @Resource
    private UserOnlineService userOnlineService;

    private static CompletionService<String> completionService = new ExecutorCompletionService<String>(ThreadPoolUtil.getPool());

    @GetMapping("/index")
    public String index() {
        return "online/user-online-list";
    }


    @GetMapping("/list")
    @ResponseBody
    public PageResultBean<UserOnline> online() {
        List<UserOnline> list = userOnlineService.list();
        return new PageResultBean<>(list.size(), list);
    }

    @PostMapping("/kickout")
    @ResponseBody
    public ResultBean forceLogout(String sessionId) {
        userOnlineService.forceLogout(sessionId);
        return ResultBean.success();
    }

    @GetMapping("/changedirection/{videoid}")
    @ResponseBody
    public String changedirection(@PathVariable("videoid") String videoid) {
        String result;
        //遍历各个ip地址
        HttpHeaders headers = new HttpHeaders();
        HttpEntity<String> requestEntity = new HttpEntity<>(null, headers);
        RestTemplate client = new RestTemplate();
        String[] ips = ipstrs.split(",");
        for (String ip : ips) {
            completionService.submit(() -> {
                ResponseEntity<String> request = client.exchange("http://"+ip + ipurl + "/" + videoid, HttpMethod.GET, requestEntity, String.class);
                return request.getBody();
            });
        }
        for (int i = 0; i < ips.length; i++) {
            try {
                result = completionService.poll(10, TimeUnit.SECONDS).get();
                log.info(ips[i]  + ipurl + "/" + videoid + ":" + result);
                if (result.equalsIgnoreCase("true")) {
                    return result;
                }
            } catch (Exception ex) {
                log.info(ips[i]+ ipurl + "/" + videoid + "error" + ex.toString());
            }
        }
        return "false";
    }

}
