/**
 * 
 */
package org.springblade.core.secure.interceptor;

import java.io.IOException;
import java.util.Objects;

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

import org.springblade.core.constant.BladeConstant;
import org.springblade.core.license.LicenseManager;
import org.springblade.core.tool.api.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.lang.NonNull;
import org.springframework.web.servlet.HandlerInterceptor;

import com.alibaba.fastjson2.JSON;

import lombok.extern.slf4j.Slf4j;

/**
 * @author wookvn
 *
 */
@Slf4j
public class LicenseInterceptor implements HandlerInterceptor {
	
	@Autowired
	private LicenseManager licenseManager;

	@Override
	public boolean preHandle(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler) {
		if(!licenseManager.validateOfLogin()) {
			write(response, R.fail("License授权文件已过期."));
			return false;
		}
		return true;
	}
	
	void write(HttpServletResponse response, R<?> result) {
		response.setCharacterEncoding(BladeConstant.UTF_8);
		response.addHeader(BladeConstant.CONTENT_TYPE_NAME, MediaType.APPLICATION_JSON_VALUE);
		response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
		try {
			response.getWriter().write(Objects.requireNonNull(JSON.toJSONString(result)));
		} catch (IOException ex) {
			log.error(ex.getMessage());
		}
	}
}
