package com.ag.web.websocket.service.topic;

import com.ag.entity.topic.RemqMsgCustom;
import com.ag.topic.BaseResponse;
import com.ag.topic.IRedisTopicCtl;
import com.ag.util.ResourceUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;

import static com.google.common.base.Preconditions.checkNotNull;
import static java.util.concurrent.Executors.newFixedThreadPool;

/**
 * @description: redis频道
 * @author: WangN
 * @create: 2019-10-15
 */
@Component
public class RedisTopicCtl implements IRedisTopicCtl {

    @Autowired
    private RestTemplate restTemplate;

    private static Logger logger = LoggerFactory.getLogger(RedisTopicCtl.class);

    private ExecutorService threads;

   // public static final String RDS_MQ_URL = "http://192.168.9.120:8080/";
    public static String RDS_MQ_URL;
//    public static final String RDS_MQ_URL = "http://197.168.1.54:8099/";
    static {
        RDS_MQ_URL = ResourceUtil.getString("system", "RDS_MQ_URL");
    }

    /**
     * 获取所有频道信息
     * @return
     */
    public String getChannel()  {
        threads = newFixedThreadPool(5);
        Callable <ResponseEntity<BaseResponse>> callable=
                () -> restTemplate.exchange(RDS_MQ_URL+"/getAllChannel",
                        HttpMethod.POST, HttpEntity.EMPTY, BaseResponse.class);
        Future<ResponseEntity<BaseResponse>> f = threads.submit(callable);
        ResponseEntity<BaseResponse> response= null;
        try {
            response = f.get();
            threads.shutdown();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return String.valueOf(response.getBody().getData());
    }

    /**
     * 发送消息
     * @param
     * @return
     */
    public void send(RemqMsgCustom remqMsgCustom, String channel){
        checkNotNull(channel,"频道名称不能为空");
        checkNotNull(remqMsgCustom.getId(),"ID不能为空");
        checkNotNull(remqMsgCustom.getCreatedBy(),"创建人不能为空");
        checkNotNull(remqMsgCustom.getCreatedOn(),"创建时间不能为空");
        checkNotNull(remqMsgCustom.getUpdatedBy(),"updatedBy不能为空");
        checkNotNull(remqMsgCustom.getUpdatedOn(),"updatedBy不能为空");
        threads = newFixedThreadPool(5);
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("msg", JSON.toJSONString(remqMsgCustom));
        jsonObject.put("channel",channel);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity<JSONObject> entity = new HttpEntity<>(jsonObject, headers);
        threads.execute(()->{
            //ResponseEntity<BaseResponse> responseEntity =
            restTemplate.exchange(RDS_MQ_URL+"/send",
                    HttpMethod.POST, entity, BaseResponse.class);
        });
        threads.shutdown();

        //return responseEntity.getBody();
    }

    /**
     * 更新频道信息
     * @return
     */
    public void putTopic(){
        //threads = newFixedThreadPool(3);
        /*HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity<JSONObject> entity = new HttpEntity<>(null, headers);*/
        //threads.execute(()->{
            restTemplate.exchange(RDS_MQ_URL+"/put",
                    HttpMethod.POST, HttpEntity.EMPTY, BaseResponse.class);
        //});
        //threads.shutdown();
        //return restTemplate.getForObject(RDS_MQ_URL+"/put",BaseResponse.class).getMsg();
    }

    /**
     * 初始化 redis 频道订阅
     */
    public void initRdsChannel(){
        restTemplate.exchange(RDS_MQ_URL+"/initListener",
                HttpMethod.POST, HttpEntity.EMPTY, BaseResponse.class);
    }

    /**
     * 初始化 用户-频道 信息到redis
     */
    public void initChannelToUser(){
        restTemplate.exchange(RDS_MQ_URL+"/initChannelToUser",
                HttpMethod.POST, HttpEntity.EMPTY, BaseResponse.class);
    }
}
