package cn.com.qmth.stmms.api.controller;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;

import cn.com.qmth.stmms.api.exception.ApiException;
import cn.com.qmth.stmms.biz.school.model.School;
import cn.com.qmth.stmms.biz.school.service.SchoolService;
import cn.com.qmth.stmms.common.controller.BaseController;

public class BaseApiController extends BaseController {

    protected static final Logger log = LoggerFactory.getLogger(BaseApiController.class);

    private static final String ERROR_MESSAGE_HEADER_KEY = "error-info";

    @Autowired
    private SchoolService schoolService;

    @ExceptionHandler
    public void exception(HttpServletResponse response, Exception ex) {
        log.error("api execute error", ex);
        response.addHeader(ERROR_MESSAGE_HEADER_KEY, StringUtils.trimToEmpty(ex.getMessage()));
        try {
            if (ex instanceof ApiException) {
                ApiException e = (ApiException) ex;
                response.sendError(e.getCode());
            } else {
                response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value());
            }
        } catch (Exception e) {
            log.error("api response senderror", e);
        }
    }

    protected JSONObject result(boolean success) {
        JSONObject obj = new JSONObject();
        obj.accumulate("success", success);
        return obj;
    }

    protected JSONObject result(boolean success, String url) {
        JSONObject obj = new JSONObject();
        obj.accumulate("success", success);
        obj.accumulate("url", url);
        return obj;
    }

    protected JSONObject result(String key, String value) {
        JSONObject obj = new JSONObject();
        obj.accumulate(key, value);
        return obj;
    }

    protected String validate(String name, String value, boolean required, int maxLength) {
        value = StringUtils.trimToNull(value);
        if (required && value == null) {
            throw ApiException.QUERY_PARAM_ERROR.replaceMessage(name + " is required");
        }
        if (value != null && maxLength > 0 && value.length() > maxLength) {
            throw ApiException.QUERY_PARAM_ERROR.replaceMessage(name + " length exceed " + maxLength);
        }
        return value;
    }

    protected String validate(String value, boolean notBlank, int maxLength) {
        if (value == null) {
            return null;
        }
        value = value.trim();
        if (notBlank && value.length() == 0) {
            return null;
        }
        if (maxLength > 0 && value.length() > maxLength) {
            return null;
        }
        return value;
    }

    protected School validate(Integer parentId, String subCode) {
        School school = schoolService.findById(parentId);
        if (StringUtils.isNotBlank(subCode)) {
            subCode = school.getCode() + "-" + subCode;
            school = schoolService.findByParentIdAndSubCode(parentId, subCode);
            if (school == null || !school.isEnable()) {
                throw ApiException.SCHOOL_NOT_ACCESSIBLED;
            }
        }
        return school;
    }

    protected boolean validateSchool(Integer parentId, Integer subId) {
        School sub = schoolService.findById(subId);
        if (sub == null) {
            return false;
        }
        return parentId.equals(subId) || sub.getParentId().equals(parentId);
    }
}
