package com.yihu.hos.monitor.service;

import com.mongodb.*;
import com.yihu.hos.common.constants.ContextAttributes;
import com.yihu.hos.core.datatype.DateUtil;
import com.yihu.hos.tenant.model.TenantSession;
import com.yihu.hos.web.framework.model.ActionResult;
import com.yihu.hos.web.framework.model.Result;
import com.yihu.hos.web.framework.model.TreeView;
import org.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by chenweida on 2016/1/27.
 */
@Service("ServerMonitorService")
public class ServerMonitorService {
    public static final String BEAN_ID = "ServerMonitorService";
    public static final String MONITOR = "monitor";
    public static final String SERVER = "server";
    public static final String HOST = "host";

    @Autowired
    private MongoOperations mongoOperations;

    @Autowired
    private Mongo mongo;

    public Result getMonitorList(HttpSession session,String host, String type, String beginTime, String endTime) {
        TenantSession tenantSession = (TenantSession)session.getAttribute(ContextAttributes.TENANT_SESSION);
        mongoOperations = new MongoTemplate(mongo, MONITOR);
        DBCollection envCollection = mongoOperations.getCollection(SERVER);
        BasicDBObject queryObject = new BasicDBObject().append(QueryOperators.AND,
                new BasicDBObject[]{
                        new BasicDBObject().append("tenant",tenantSession.getTenant()),
                        new BasicDBObject().append("host",host),
                        new BasicDBObject().append("type",type),
                        new BasicDBObject().append("create_time",
                                new BasicDBObject().append(QueryOperators.GTE, DateUtil.toTimestamp(beginTime))),
                        new BasicDBObject().append("create_time",
                                new BasicDBObject().append(QueryOperators.LT, DateUtil.toTimestamp(endTime)))});

        JSONArray result = new JSONArray();
        DBCursor cursor = envCollection.find(queryObject);
        while(cursor.hasNext()) {
            DBObject dbObject = cursor.next();
            dbObject.removeField("_id");
            result.put(dbObject);
        }

        ActionResult actionResult = new ActionResult();
        actionResult.setData(result);
        return actionResult;
    }

    public Result getMonitorDetail(HttpSession session,String host, String type, String date) {
        TenantSession tenantSession = (TenantSession)session.getAttribute(ContextAttributes.TENANT_SESSION);
        mongoOperations = new MongoTemplate(mongo, MONITOR);
        DBCollection envCollection = mongoOperations.getCollection(SERVER);
        BasicDBObject queryObject = new BasicDBObject().append(QueryOperators.AND,
                new BasicDBObject[]{
                        new BasicDBObject().append("tenant",tenantSession.getTenant()),
                        new BasicDBObject().append("host", host),
                        new BasicDBObject().append("type", type),
                        new BasicDBObject().append("create_time",new BasicDBObject().append(QueryOperators.LTE, DateUtil.toTimestamp(date)))});

        Map result = new HashMap<>();
        DBCursor cursor = envCollection.find(queryObject).sort(new BasicDBObject("create_time",-1)).limit(1);
        while(cursor.hasNext()) {
            DBObject dbObject = cursor.next();
            dbObject.removeField("_id");
            result = dbObject.toMap();
        }

        ActionResult actionResult = new ActionResult();
        actionResult.setData(result);
        return actionResult;
    }



    public Result getHosts() {
        List<Map<String,Object>> result = new ArrayList<>();
        mongoOperations = new MongoTemplate(mongo, MONITOR);
        DBCollection envCollection = mongoOperations.getCollection(HOST);
        DBCursor cursor = envCollection.find();
        while(cursor.hasNext()) {
            DBObject dbObject = cursor.next();
            Map<String,Object> hostMap = new HashMap<>();
            hostMap.put("host",dbObject.get("host"));
            hostMap.put("name",dbObject.get("name"));
            result.add(hostMap);
            hostMap=null;
        }
        ActionResult actionResult = new ActionResult();
        actionResult.setData(result);
        return actionResult;
    }

    /**
     * 獲取服務器列表 树
     * @return
     * @throws Exception
     */
    public Result getServerTreeList(HttpSession session) throws Exception {
        List<TreeView> treeList = new ArrayList<>();
        TenantSession tenantSession = (TenantSession)session.getAttribute(ContextAttributes.TENANT_SESSION);
        mongoOperations = new MongoTemplate(mongo, MONITOR);
        DBCollection envCollection = mongoOperations.getCollection(HOST);
        //查询条件
        BasicDBObject queryObject = new BasicDBObject().append(QueryOperators.AND,
                new BasicDBObject[]{
                        new BasicDBObject().append("tenant",tenantSession.getTenant())});

        DBCursor cursor = envCollection.find(queryObject);

        while(cursor.hasNext()) {
            DBObject dbObject = cursor.next();
            TreeView rootTree = new TreeView();
            rootTree.setId(dbObject.get("host").toString());
            rootTree.setPid("-1");
            rootTree.setText(dbObject.get("name").toString()+"/"+dbObject.get("host").toString());
            treeList.add(rootTree);
        }

        JSONArray jsonArray = new JSONArray(treeList);
        return Result.success(jsonArray.toString());
    }

}
