/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.github.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/

package com.cesgroup.cesmonitor.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cesgroup.cesmonitor.bean.TopologicalInfo;
import com.cesgroup.cesmonitor.service.MapService;
import com.cesgroup.cesmonitor.service.OverviewService;

/**
 * 监控总览
 *
 */
@Controller
@RequestMapping(value = "/map")
public class MapController {

    @Autowired
    MapService mapService;

    @Autowired
    OverviewService overviewService;

    /**
     * 根据主机创建拓扑图
     *
     * @param model
     *            模型对象
     * @return 创建界面
     */
    @RequestMapping(value = "createFromHosts")
    public String createFromHosts(Model model) {
        //mapService.createFromHosts();
        //      return "redirect:../php/sysmaps.php";
        return "map/createFromHosts";
    }

    /**
     * 创建主机拓扑图
     *
     * @param ips
     *            网关IP地址，多个IP用“,”分割
     * @param name
     *            拓扑图名称
     * @param layoutFlag
     *            布局方式1:基本布局；1：伞型；2：扇形
     * @return 1：创建成功；其他：错误消息
     */
    @RequestMapping(value = "doCreateFromHosts")
    @ResponseBody
    public String doCreateFromHosts(String ips, String name, int layoutFlag) {
        try {
            TopologicalInfo toplogicInfo = overviewService.findToplogicalInfoByNameService(name);
            List<String> ipList = new ArrayList<String>();
            for (String ip : ips.split(",")) {
                if (ip.trim().equals("")) {
                    continue;
                }
                ipList.add(ip);
            }
            if (toplogicInfo != null) { //判断是否存在相应的拓扑图
                //                ZabbixApi zabbixApi = Util.getLoginUser().getZabbixApi();
                //                MapDeleteRequest request = new MapDeleteRequest();
                //                request.addMapId(Integer.parseInt(toplogicInfo.getSysmapId())); //删除拓扑图，进行覆盖
                //                zabbixApi.map().delete(request);
                //更新
                mapService.createFromHostsUpdate(Integer.parseInt(toplogicInfo.getSysmapId()), ipList);
            } else {
                //创建
                mapService.createFromHosts(name, ipList, layoutFlag);
            }

            return "1";
        } catch (Exception e) {
            e.printStackTrace();
            if (e.getMessage() == null) {
                return "输入的网关不存在或IP地址错误";
            } else {
                return e.getMessage();
            }

        }
    }

    /**
     * 根据IT服务创建拓扑图
     *
     * @param model
     *            模型
     * @param serviceId
     *            IT服务节点ID
     * @return 判断拓扑图存在性
     */
    @RequestMapping(value = "createFromITService")
    public void createFromITService(Model model, Integer serviceId, HttpServletRequest request,
        HttpServletResponse response) {
        PrintWriter out;
        try {
            response.setHeader("Content-type", "text/html;charset=UTF-8");
            TopologicalInfo toplogicInfo = overviewService.findToplogicalInfoByServiceIdService(serviceId);
            out = response.getWriter();
            if (toplogicInfo == null) {
                mapService.createFromITService(serviceId);
                out.write("<script>window.location.href='../php/sysmaps.php?map_type=2'</script>");
            } else {
                out.write("<script src=" + request.getContextPath() + "/js/jquery.1.10.1.min.js" + "></script>");
                out.write("<script src=" + request.getContextPath() + "/js/map.js" + "></script>");
                out.write("<script>if(confirm('拓扑图已存在，是否覆盖?')) {");
                out.write("testA(" + serviceId + ")}");
                out.write("else {history.back();}</script>");
                out.flush();
                out.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     *
     * @param model
     *            模型
     * @param serviceId
     *            IT服务节点ID
     */
    @RequestMapping(value = "createFromIT")
    public void createFromIT(Model model, Integer serviceId) {
        TopologicalInfo toplogicInfo = overviewService.findToplogicalInfoByServiceIdService(serviceId);
        try {
            if (toplogicInfo != null) {
                //                ZabbixApi zabbixApi = Util.getLoginUser().getZabbixApi();
                //                MapDeleteRequest request = new MapDeleteRequest();
                //                request.addMapId(Integer.parseInt(toplogicInfo.getSysmapId())); //删除拓扑图，进行覆盖
                //                zabbixApi.map().delete(request);
                mapService.createFromITServiceUpdate(Integer.parseInt(toplogicInfo.getSysmapId()), serviceId);
            } else {
                mapService.createFromITService(serviceId);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 将拓扑图添加到监控总览
     *
     * @param model
     *            模型
     * @param sysmapid
     *            拓扑图id
     * @return 转发到监控总览页面
     */
    @RequestMapping(value = "addToOverview")
    public String addToOverview(Model model, Integer sysmapid) {
        mapService.addToOverview(sysmapid);
        return "redirect:../overview/index";
    }

    /**
     * 覆盖map
     *
     * @param request
     *            请求
     * @param response
     *            响应
     */
    @RequestMapping(value = "coverMap")
    public void coverMap(HttpServletRequest request, HttpServletResponse response, String name) {
        response.setCharacterEncoding("UTF-8");
        TopologicalInfo toplogicInfo = overviewService.findToplogicalInfoByNameService(name); //查询是否存在名称为name的拓扑图
        if (toplogicInfo == null) {
            return;
        } else {
            PrintWriter out;
            try {
                out = response.getWriter();
                out.write("拓扑图" + name + "已存在，是否覆盖?");
                out.flush();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 自动创建
     *
     * @param name
     *            拓扑图名称
     * @param ip
     *            核心交换机IP地址
     * @param community
     *            SNMP community
     * @return
     */
    @RequestMapping(value = "autoCreate")
    public String autoCreate(String name, String ip, String community) {
        if (community == null) {
            community = "public";
        }
        TopologicalInfo toplogicInfo = overviewService.findToplogicalInfoByNameService(name);
        if (toplogicInfo != null) { //判断是否存在相应的拓扑图
            mapService.createAutoUpdate(Integer.parseInt(toplogicInfo.getSysmapId()), ip, community);
        } else {
            mapService.createAuto(name, ip, community);
        }

        return "redirect:../php/sysmaps.php?map_type=1";
    }

    /**
     * 自动更新
     *
     * @param sysmapid
     *            拓扑图Id
     * @param ip
     *            核心交换机IP地址
     * @param community
     *            SNMP community
     * @return
     */
    @RequestMapping(value = "autoCreateUpdate")
    public String autoCreateUpdate(Integer sysmapid, String ip, String community) {
        if (community == null) {
            community = "public";
        }
        mapService.createAutoUpdate(sysmapid, ip, community);
        return "redirect:../php/zabbix.php?map_type=1&action=map.view&sysmapid=" + sysmapid;
    }
}
