package cn.myapps.runtime.system.monitor.controller;

import cn.myapps.common.util.StringUtil;
import cn.myapps.runtime.system.monitor.util.SystemMonitorUtil;
import com.sun.management.OperatingSystemMXBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.MemoryUsage;
import java.lang.management.ThreadMXBean;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Controller
@Scope("prototype")
@RequestMapping(value = "/api")
public class SystemMonitorController {
	
	@Autowired
	public HttpServletRequest request;
	
	ThreadMXBean threadMXBean=ManagementFactory.getPlatformMXBean(ThreadMXBean.class);
	
	OperatingSystemMXBean osBean=ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class);

	MemoryMXBean memBean=ManagementFactory.getPlatformMXBean(MemoryMXBean.class);
	
	
	@ResponseBody
	@GetMapping(value = "/system/monitor/time",produces=MediaType.APPLICATION_JSON_UTF8_VALUE)
	public Object getProcessCpuLoad() throws Exception{
		int mb=1024*1024;
		int threadNum=threadMXBean.getThreadCount();
		
		Map<String,Object> hashMap=new HashMap<String,Object>();
		DecimalFormat df=new DecimalFormat("0.00");
		double processCpuLoad=osBean.getProcessCpuLoad();
		processCpuLoad=processCpuLoad*100;
		if(processCpuLoad<0) processCpuLoad=0;
		//物理内存使用量
		long freePhysicalMemorySize=osBean.getFreePhysicalMemorySize();
		long totalPhysicalMemorySize=osBean.getTotalPhysicalMemorySize();
		String physicalMemorySizeUse=df.format((float)(totalPhysicalMemorySize-freePhysicalMemorySize)/mb); 
		hashMap.put("cpuLoad", Double.valueOf(processCpuLoad));
		hashMap.put("memorySizeUse", Double.valueOf(physicalMemorySizeUse));
		hashMap.put("totalMemorySize", totalPhysicalMemorySize/mb);
		hashMap.put("threadNum", threadNum);
		
		//非对内存数量
		
		MemoryUsage heap=memBean.getHeapMemoryUsage();
		MemoryUsage nonHeap=memBean.getNonHeapMemoryUsage();
		
		long heapSizeUsed=heap.getUsed()/mb;
		long nonHeapSizeUsed=nonHeap.getUsed()/mb;
		
		hashMap.put("heapSizeUsed", heapSizeUsed);
		hashMap.put("nonHeapSizeUsed", nonHeapSizeUsed);
		
		
        return hashMap;
	}
	
	
	@ResponseBody
	@GetMapping(value = "/systemMonitor",produces=MediaType.APPLICATION_JSON_UTF8_VALUE)
	public Object getSystemMonitor() throws Exception{
		String contextPath=System.getProperty("java.io.tmpdir");
		//读取文本
		String filePath=contextPath + File.separator + "systemMonitor.txt";
		List<String> lists= SystemMonitorUtil.readFile(filePath);
		StringBuffer stbr=new StringBuffer();
		//找出指针对应的位置
		int beginIndex=0;
		int endIndex=lists.size()-1;
		//获取前台传过来的时间
		String minuteTime=request.getParameter("time");
		if(!StringUtil.isBlank(minuteTime)){
			List<String> litstTemp=new ArrayList<String>();
			//因为每30s记录1次文本，所以次数*2
			int count=Integer.valueOf(minuteTime)*2;
			//从后往前走
			if(lists.size()>count){
				beginIndex=lists.size()-1-count;
			}
			System.out.println(minuteTime);
			litstTemp.addAll(lists.subList(beginIndex, endIndex));
			stbr.append("[");
			for (String string : litstTemp) {
				stbr.append(string).append(",");
			}
			stbr.setLength(stbr.length()-1);
			stbr.append("]");
			return stbr.toString();
		}else{
			//从文本拿出的数据进行帅选
			if(lists.size()>100){
				beginIndex=endIndex-100-1;
				List<String> litstTemp=new ArrayList<String>();
				litstTemp.addAll(lists.subList(beginIndex, endIndex));
				stbr.append("[");
				for (String string : litstTemp) {
					stbr.append(string).append(",");
				}
				stbr.setLength(stbr.length()-1);
				stbr.append("]");
				return stbr.toString();
			}else{
				stbr.append("[");
				for (String string : lists) {
					stbr.append(string).append(",");
				}
				stbr.setLength(stbr.length()-1);
				stbr.append("]");
				return stbr.toString();
			}
		}
//		return lists;
	}
}
