package com.tzy.common.config.handle;

import com.tzy.common.config.CommonConfig;
import org.slf4j.Logger;
import org.springframework.web.servlet.mvc.condition.RequestCondition;
import org.teasoft.honey.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ApiVesrsionCondition implements RequestCondition<ApiVesrsionCondition> {

	private static final Logger LOG= org.slf4j.LoggerFactory.getLogger(ApiVesrsionCondition.class);
	private final static Pattern VERSION_PREFIX_PATTERN = Pattern.compile("v\\d*\\.\\d*|v\\d+");


	private double apiVersion;


	public ApiVesrsionCondition(double apiVersion) {
		this.apiVersion = apiVersion;

	}

	@Override
	public ApiVesrsionCondition combine(ApiVesrsionCondition other) {
		return new ApiVesrsionCondition(other.getApiVersion());
	}

	@Override
	public ApiVesrsionCondition getMatchingCondition(HttpServletRequest request) {
		if(CommonConfig.isDevEnv()){
			return this;
		}
		Matcher m = VERSION_PREFIX_PATTERN.matcher(request.getRequestURI());
		Boolean flag = m.find();
		if (flag) {
			String group = m.group();
			String v = group.substring(1, group.length());
			if(StringUtils.isEmpty(v)){
				return null;
			}
			Double version = Double.parseDouble(v);
			if (version == 0) {
				if(version <= this.apiVersion){
					return this;
				}
			}
			if (version >= this.apiVersion) {
				return this;
			}

		}
		return null;
	}

	@Override
	public int compareTo(ApiVesrsionCondition other, HttpServletRequest request) {
		LOG.debug("other:{}",other.getApiVersion());
		LOG.debug("api version:{}",this.apiVersion);
		if(other.getApiVersion() <= this.apiVersion  ){
			return -1;
		}
		return 0;
	}

	public double getApiVersion() {
		return apiVersion;
	}

}
