/**
 * Project Name:access-activity-web File Name:ServerController.java Package Name:com.duiba.activity.accessweb.controller
 * Date:2017年1月9日下午2:53:44 Copyright (c) 2017, duiba.com.cn All Rights Reserved.
 */

package com.duiba.tuia.youtui.web.controller;

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

import cn.com.duiba.tuia.activity.center.api.remoteservice.RemoteIpService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.duiba.tuia.youtui.web.exception.ActivityRuntimeException;

import cn.com.duiba.wolf.perf.timeprofile.RequestTool;

/**
 * ClassName:ServerController <br/>
 * Date: 2017年1月9日 下午2:53:44 <br/>.
 *
 * @author zp
 * @see
 * @since JDK 1.6
 */
@Controller
@RequestMapping("/server")
public class ServerController {

    /**
     * The status switch.
     */
    private Boolean statusSwitch = false;

    @Autowired
    private RemoteIpService remoteIpService;

    /**
     * Check.
     *
     * @param request  the request
     * @param response the response
     * @return the string
     */
    @RequestMapping("/check")
    @ResponseBody
    public String check(HttpServletRequest request, HttpServletResponse response) {
        if (statusSwitch) {
            JSONObject json = new JSONObject();
            json.put("statusSwitch", statusSwitch);
            return json.toJSONString();
        } else {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return null;
        }
    }

    /**
     * Switch check.
     *
     * @param request the request
     * @return the string
     */
    @RequestMapping("/switchCheck")
    @ResponseBody
    public String switchCheck(HttpServletRequest request) {
        if (!RequestTool.isLocalRequest(request)) {
            throw new ActivityRuntimeException("无权限");
        }
        String type = request.getParameter("type");
        statusSwitch = !"close".equals(type);
        JSONObject json = new JSONObject();
        json.put("statusSwitch", statusSwitch);
        return json.toJSONString();
    }

    @RequestMapping("/ip")
    @ResponseBody
    public String ip(HttpServletRequest request) {
        JSONObject json = new JSONObject();
        String ip = request.getParameter("ip");
        if (StringUtils.isBlank(ip)) {
            ip = RequestTool.getIpAddr(request);
        }
        json.put("ip", ip);
        json.put("ipInfo", this.remoteIpService.findByIp(ip));
        return json.toJSONString();
    }
}
