package com.bocloud.ims.service.utils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.bocloud.cmp.driver.monitor.MonitorDriver;
import com.bocloud.cmp.model.MonitorCategoryModel;
import com.bocloud.cmp.model.MonitorModel;
import com.bocloud.common.model.BocloudResult;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

public class VmwareMonitorUtils {

	private MonitorDriver monitorDriver;

	public VmwareMonitorUtils(MonitorDriver monitorDriver) {
		super();
		this.monitorDriver = monitorDriver;
	}

	@SuppressWarnings("unchecked")
	public BocloudResult getPerformance(JSONObject object, String vendor, List<String> types, String category) {
		BocloudResult result = monitorDriver.query(vendor, object.getString("name"), category, types,
				object.getString("time"));
		Map<String, Object> resultMap = Maps.newHashMap();
		if (result.isFailed() || null == result.getData()) {
			for (String type : types) {
				resultMap.put(type, new MonitorModel());
			}
			return new BocloudResult(true, resultMap, "查询成功");
		}
		Map<String, Object> maps = JSONObject.parseObject(JSONObject.toJSONString(result.getData()), HashMap.class);
		for (String type : types) {
			if (!maps.containsKey(type)) {
				resultMap.put(type, new MonitorModel());
				continue;
			}
			if (type.equals("DISK")) {
				resultMap.put(type, maps.get(type));
			} else {
				int value = type.equals("SYSTEM") ? 100000 : 100;
				MonitorModel model = JSONObject.parseObject(JSONObject.toJSONString(maps.get(type)),
						MonitorModel.class);
				List<MonitorCategoryModel> monitors = model.getValues();
				List<MonitorCategoryModel> values = Lists.newArrayList();
				for (MonitorCategoryModel monitor : monitors) {
					List<String> oldDatas = monitor.getData();
					List<String> newDatas = Lists.newArrayList();
					for (String data : oldDatas) {
						newDatas.add(new BigDecimal(Float.valueOf(data))
								.divide(new BigDecimal(value), 2, RoundingMode.HALF_UP).toString());
					}
					values.add(new MonitorCategoryModel(monitor.getName(), newDatas));
				}
				resultMap.put(type, new MonitorModel(model.getKeys(), values));
			}
		}
		return new BocloudResult(true, resultMap, "查询成功");
	}

}
