package com.yihu.hos.common.scheduler;

import com.yihu.hos.common.util.MongodbUtil;
import com.yihu.hos.common.util.SigarUtil;
import com.yihu.hos.core.datatype.DateUtil;
import com.yihu.hos.core.log.Logger;
import com.yihu.hos.core.log.LoggerFactory;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.bson.Document;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 *  服务器性能数据采集定时器
 * @author HZY
 * @vsrsion 1.0
 * Created at 2016/10/11.
 */
@Component
public class EnvScheduler {

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

    @Scheduled(cron="0 0/1 * * * ?") //每分钟执行一次
    public void statusCheck() {
        System.out.println("每分钟执行一次。开始============================================");
        //TODO 采集服务器健康监控指标数据 statusTask.healthCheck();
        collectEnvHealth();
        System.out.println("每分钟执行一次。结束。");
    }

    public String collectEnvHealth(){
        MongodbUtil monoEnv = new MongodbUtil("envHealth");
        try {
            Document result = new Document();
            result.put("create_date", DateUtil.getCurrentString(DateUtil.DEFAULT_YMDHMSDATE_FORMAT));
            result.put("create_time", new Date());

            //cpu
            JSONObject cpu = JSONObject.fromObject( SigarUtil.cpu());
            result.put("data",cpu);
            monoEnv.insert("cpu",result);
            //内存
            JSONObject memory = JSONObject.fromObject( SigarUtil.memory());
            result.put("data",memory);
            monoEnv.insert("memory",result);
            //硬盘
            List<JSONObject> files = JSONArray.fromObject( SigarUtil.file());
            result.put("data",files);
            monoEnv.insert("files", result);
            //网络
            JSONObject net = JSONObject.fromObject( SigarUtil.net());
            result.put("data",net);
            monoEnv.insert("net",result);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }









//    @Scheduled(fixedRate=10000)
//    public void testTasks() {
//        System.out.println("每10秒执行一次。开始……");
//        //statusTask.healthCheck();
//        System.out.println("每10秒执行一次。结束。");
//    }

}
