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.sql.Timestamp;
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 = "log";
    public static final String SERVER = "server";
    public static final String HOST = "host";

    @Autowired
    private MongoOperations mongoOperations;

    @Autowired
    private MongoClient mongoClient;

    public Result getMonitorList(HttpSession session, String host, String type, String beginTime, String endTime) {
        TenantSession tenantSession = (TenantSession) session.getAttribute(ContextAttributes.TENANT_SESSION);
        mongoOperations = new MongoTemplate(mongoClient, MONITOR);
        DBCollection envCollection = mongoOperations.getCollection(SERVER);
        Timestamp begin = DateUtil.toTimestamp(beginTime);
        Timestamp end = DateUtil.toTimestamp(endTime);
        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("create_date", new BasicDBObject().append(QueryOperators.GTE, beginTime)
                                .append(QueryOperators.LT, endTime))
                });

        List<DBObject> result = new ArrayList<>();
        DBCursor cursor = envCollection.find(queryObject);
        while (cursor.hasNext()) {
            DBObject dbObject = cursor.next();
            dbObject.removeField("_id");
            result.add(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(mongoClient, MONITOR);
        DBCollection envCollection = mongoOperations.getCollection(SERVER);
        Timestamp timestamp = DateUtil.toTimestamp(date);
        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("create_date", new BasicDBObject(QueryOperators.LTE, date))});

        Map result = new HashMap<>();
        DBCursor cursor = envCollection.find(queryObject).sort(new BasicDBObject("create_date", -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(mongoClient, 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(mongoClient, 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());
    }

}
