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

import com.duiba.tuia.youtui.web.constant.ErrorCode;
import com.duiba.tuia.youtui.web.exception.ActivityException;
import com.duiba.tuia.youtui.web.model.Result;
import com.duiba.tuia.youtui.web.service.MengMaService;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
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.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("/config")
public class ConfigController extends BaseController {
    @Autowired
    private MengMaService mengMaService;

    @RequestMapping(value = "/getMengMa", method = {RequestMethod.GET})
    @ResponseBody
    public int getMengMaQpsLimit(HttpServletRequest request) {
        return this.mengMaService.getQpsLimit();
    }

    @RequestMapping(value = "/setMengMa", method = {RequestMethod.GET})
    @ResponseBody
    public Result<Object> setMengMaQpsLimit(HttpServletRequest request,String password,String times) {


        try {
            if (!checkPassword(password)) {
                return failResult(new ActivityException(ErrorCode.E0100009));
            }
            int timesInt = checkTimes(times);
            this.mengMaService.setQpsLimit(timesInt);

            return successResult();
        } catch (Exception e) {
            return failResult(e);
        }

    }

    private int checkTimes(String times) throws ActivityException {
        if (!StringUtils.isNumeric(times)) {
            throw new ActivityException(ErrorCode.E0000001);
        }
        int timesInt = Integer.valueOf(times);
        if (timesInt < -1) {
            throw new ActivityException(ErrorCode.E0000001);
        }
        return timesInt;
    }

    private boolean checkPassword(String password) {
        if (StringUtils.isBlank(password)) {
            return false;
        }
        DateTime date = new DateTime();
        int time = date.getYear()+date.getMonthOfYear()+date.getDayOfMonth()+date.getHourOfDay();
        String expec = "wuboisthemosthandsome" + time;

        return expec.equals(password);

    }
    
}
