/**
 * <p>Copyright:Copyright(c) 2017</p>
 * <p>Company:上海中信信息发展股份有限公司</p>
 * <p>包名:com.cesgroup.cesmonitor.service.map</p>
 * <p>文件名:TwoColumnLayout.java</p>
 * <p>创建时间:2017年5月23日 上午9:52:30</p>
 * <p>作者:zhang.erwei</p>
 */

package com.cesgroup.cesmonitor.service.map;

import java.util.Map;

import com.zabbix4j.map.MapElementObject;
import com.zabbix4j.map.MapUpdateRequest;

/**
 * 两列布局
 *
 * @author zhang.erwei
 * @version 1.0.0 2017年5月23日
 */
public class TwoColumnLayout implements Layout {

    /**
     * 计算拓扑图高度
     * @param groups 主机组
     * @return 拓扑图高度
     * @throws Exception 异常对象
     */
    private int caculateMapHeight(Map<String, HostGroup> groups) throws Exception {
        int i = 0;
        for (String ipPrefix : groups.keySet()) {
            HostGroup hg = groups.get(ipPrefix);
            i += hg.getHosts().size() / 2 + hg.getHosts().size() % 2;
        }
        if (i < groups.keySet().size()) {
            i = groups.keySet().size();
        }
        return MapCreateFromHosts.HEIGHT_PER_NODE * (i + 2);
    }

    @Override
    public void doLayout(MapUpdateRequest.Params map, Map<String, HostGroup> groups) throws Exception {
        map.setHeight(caculateMapHeight(groups));
        map.setWidth(1000);
        int y = 0;
        int i = 0;
        for (String ipPrefix : groups.keySet()) {
            HostGroup group = groups.get(ipPrefix);
            Host gateway = group.getGateway();
            MapElementObject from = null;
            if (gateway != null) {
                from = gateway.getMapElementObject();
                from.setX(450);
                from.setY(y + group.getHosts().size() / 4 * MapCreateFromHosts.HEIGHT_PER_NODE);
            }
            for (Host host : group.getHosts()) {
                MapElementObject to = host.getMapElementObject();
                i++;
                if (i % 2 == 0) {
                    to.setX(200);
                    to.setY(y);
                } else {
                    to.setX(700);
                    to.setY(y);
                    y = y + MapCreateFromHosts.HEIGHT_PER_NODE;
                }
            }
        }

    }
}