package com.lightinit.hsdataplatformresdir.controller;

import com.lightinit.hsdataplatformresdir.common.CharEncoding;
import com.lightinit.hsdataplatformresdir.common.HttpTookitUtils;
import com.lightinit.hsdataplatformresdir.common.TripleDESUtilsPro;
import com.lightinit.hsdataplatformresdir.json.pojo.BrokerEntity;
import com.lightinit.hsdataplatformresdir.json.pojo.BrokerMessageEntity;
import com.lightinit.hsdataplatformresdir.json.pojo.JsonResult;
import com.lightinit.hsdataplatformresdir.json.pojo.ListResult;
import com.lightinit.hsdataplatformresdir.json.pojo.actviemq.BrokerBrowseRequest;
import com.lightinit.hsdataplatformresdir.json.pojo.actviemq.ObjectViewBeanRequest;
import com.lightinit.hsdataplatformresdir.json.pojo.actviemq.QueuesBrowsRequest;
import com.lightinit.hsdataplatformresdir.json.pojo.actviemq.RequestValueEntity;
import com.lightinit.hsdataplatformresdir.entity.Queueserver;
import com.lightinit.hsdataplatformresdir.service.IActiveMQService;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by Mr.Yao on 2017/12/5.
 */
@Controller
@RequestMapping("/activemq")
public class ActiveMQController {
    @Autowired
    private IActiveMQService activeMQService;
    @RequestMapping(value = "view/broker.action",method = RequestMethod.GET)
    public String print_activemq_view_broker(){
        return "activemq/server";
    }

    @ResponseBody
    @RequestMapping(value = "json/server.action",method = RequestMethod.GET)
    public ListResult<Queueserver> print_JSON_ActiveMQ_Server(@RequestParam(defaultValue = "") String host) {
        ListResult<Queueserver> result = new ListResult<Queueserver>();
        result.setRows(activeMQService.queryServer(host));
        if (result.getRows()!=null){
            result.setTotal(result.getRows().size());
        }else{
            result.setTotal(0);
        }
        return result;
    }
    @ResponseBody
    @RequestMapping(value = "json/broker.action",method = RequestMethod.GET)
    public ListResult<BrokerEntity> print_JSON_ActiveMQBroker(@RequestParam(defaultValue = "localhost") String host, @RequestParam(defaultValue = "8161") int port, @RequestParam(defaultValue = "localhost") String broker, @RequestParam(defaultValue = "") String token){
        ListResult<BrokerEntity> result=new ListResult<BrokerEntity>();
        if(StringUtils.isEmpty(host) || host.equalsIgnoreCase("localhost"))
            return result;
        // TODO: 2017/12/29 利用RESTful接口获取数据
        try {
            if(StringUtils.isEmpty(token)==false){
                token= TripleDESUtilsPro.decryptMode(token)+"@";
            }
            List<BrokerEntity> brokeList=new ArrayList<BrokerEntity>();
            String brokerUrl=String.format("http://%s%s:%d/api/jolokia/read/org.apache.activemq:type=Broker,brokerName=%s/Queues",token, host, port,broker);
            String responseBody= HttpTookitUtils.doGet(brokerUrl,null, CharEncoding.UTF8,"application/json");
            ObjectMapper objectMapper = new ObjectMapper();
            QueuesBrowsRequest itemList = objectMapper.readValue(responseBody, QueuesBrowsRequest.class);
            if(itemList!=null && itemList.getValue()!=null) {
                for (Map<String,String> mapObj : itemList.getValue()) {
                    if(mapObj.containsKey("objectName") && mapObj.get("objectName")!=null) {
                        String objectName = mapObj.get("objectName");
                        if (StringUtils.isEmpty(objectName)==false) {
                            BrokerEntity item = new BrokerEntity();
                            String beanName = objectName.replace("org.apache.activemq:", "");
                            String[] objectItemList = beanName.split(",");
                            if (objectItemList != null && objectItemList.length > 0) {
                                for (String _obj : objectItemList) {
                                    if (_obj.startsWith("brokerName=")) {

                                    } else if (_obj.startsWith("destinationName=")) {
                                        item.setName(_obj.replace("destinationName=", ""));
                                    } else if (_obj.startsWith("destinationType=")) {

                                    } else if (_obj.startsWith("type=")) {

                                    }
                                }
                            }
                            String objectViewRequestUrl = String.format("http://%s%s:%d/api/jolokia/read/%s",token, host, port, objectName);
                            String objectViewResponseBody = HttpTookitUtils.doGet(objectViewRequestUrl, null, CharEncoding.UTF8, "application/json");
                            ObjectViewBeanRequest objectViewBeanList = objectMapper.readValue(objectViewResponseBody, ObjectViewBeanRequest.class);
                            if (objectViewBeanList != null && objectViewBeanList.getValue() != null) {
                                Object mQueueSize = objectViewBeanList.getValue().get("QueueSize");
                                if (mQueueSize != null) {
                                    item.setSize(Long.valueOf(mQueueSize.toString()));
                                }
                                Object mConsumers = objectViewBeanList.getValue().get("ConsumerCount");
                                if (mConsumers != null) {
                                    item.setConsumers(Long.valueOf(mConsumers.toString()));
                                }
                                Object mEnqueue = objectViewBeanList.getValue().get("EnqueueCount");
                                if (mEnqueue != null) {
                                    item.setEnqueue(Long.valueOf(mEnqueue.toString()));
                                }
                                Object mDequeue = objectViewBeanList.getValue().get("DequeueCount");
                                if (mDequeue != null) {
                                    item.setDequeue(Long.valueOf(mDequeue.toString()));
                                }
                                brokeList.add(item);
                            }
                        }
                    }
                }
            }
            result.setTotal(brokeList.size());
            result.setRows(brokeList);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
    @ResponseBody
    @RequestMapping(value = "json/broker/destination.action",method = RequestMethod.GET)
    public ListResult<BrokerMessageEntity> print_JSON_ActiveMQBroker_Destination(@RequestParam(defaultValue = "localhost") String host, @RequestParam(defaultValue = "8161") int port, @RequestParam(defaultValue = "localhost") String broker, @RequestParam(defaultValue = "") String queue, @RequestParam(defaultValue = "") String token) {
        ListResult<BrokerMessageEntity> result = new ListResult<BrokerMessageEntity>();
        if (StringUtils.isEmpty(host) || host.equalsIgnoreCase("localhost") || StringUtils.isEmpty(queue))
            return result;
        try {
            if(StringUtils.isEmpty(token)==false){
                token= TripleDESUtilsPro.decryptMode(token)+"@";
            }
            List<BrokerMessageEntity> brokeList = new ArrayList<BrokerMessageEntity>();
            // TODO: 2017/12/29 RESTful获取队列消息
            String brokerUrl=String.format("http://%s%s:%d/api/jolokia/exec/org.apache.activemq:type=Broker,brokerName=%s,destinationType=Queue,destinationName=%s/browse()/",token, host, port,broker,queue);
            String responseBody= HttpTookitUtils.doGet(brokerUrl,null, CharEncoding.UTF8,"application/json");
            ObjectMapper objectMapper = new ObjectMapper();
            BrokerBrowseRequest itemList = objectMapper.readValue(responseBody, BrokerBrowseRequest.class);
            if(itemList!=null && itemList.getValue()!=null){
                for (RequestValueEntity item:itemList.getValue()) {
                    BrokerMessageEntity _item = new BrokerMessageEntity();
                    if (item.getJMSMessageID() != null) {
                        _item.setMessageid(item.getJMSMessageID());
                    }
                    if (item.getJMSCorrelationID() != null) {
                        _item.setCorrelationid(item.getJMSCorrelationID());
                    }
                    _item.setPriority(String.valueOf(item.getJMSPriority()));
                    _item.setRedelivered(String.valueOf(item.isJMSRedelivered()));
                    if (item.getJMSReplyTo() != null) {
                        _item.setReplyto(item.getJMSReplyTo());
                    }
                    if (item.getJMSTimestamp() != null) {
                        _item.setTimestamp(item.getJMSTimestamp());
                    }
                    if (item.getJMSType()!= null) {
                        _item.setType(item.getJMSType());
                    }
                    if (item.getText() != null) {
                        _item.setMessage(item.getText());
                    }
                    brokeList.add(_item);
                }
            }
            result.setTotal(brokeList.size());
            result.setRows(brokeList);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }


    @ResponseBody
    @RequestMapping(value = "json/message/delete.action",method = RequestMethod.GET)
    public JsonResult print_JSON_ActiveMQBroker_Message_Delete(@RequestParam(defaultValue = "localhost") String host, @RequestParam(defaultValue = "8161") int port, @RequestParam(defaultValue = "localhost") String broker, @RequestParam(defaultValue = "") String queue, @RequestParam(defaultValue = "") String token, @RequestParam(defaultValue = "") String message) {
        JsonResult result = new JsonResult();
        if (StringUtils.isEmpty(host) || host.equalsIgnoreCase("localhost") || StringUtils.isEmpty(queue) || StringUtils.isEmpty(message)) {
            result.setMessage("非法请求！");
            result.setStatus(0);
            return result;
        }
        try {
            if(StringUtils.isEmpty(token)==false){
                token= TripleDESUtilsPro.decryptMode(token)+"@";
            }
            String brokerUrl=String.format("http://%s%s:%d/api/jolokia/exec/org.apache.activemq:type=Broker,brokerName=%s,destinationType=Queue,destinationName=%s/removeMatchingMessages(java.lang.String)/JMSMessageID='%s'",token, host, port,broker,queue,message);
            String responseBody= HttpTookitUtils.doGet(brokerUrl,null, CharEncoding.UTF8,"application/json");
            System.out.println(responseBody);
            result.setMessage("删除成功！");
            result.setStatus(1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
