/*
 * Copyright (c) 2018 無色眼镜
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package club.dawdler.clientplug.web.fire;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import club.dawdler.clientplug.web.annotation.Controller;
import club.dawdler.clientplug.web.annotation.JsonIgnoreNull;
import club.dawdler.clientplug.web.annotation.RequestBody;
import club.dawdler.clientplug.web.annotation.RequestMapping;
import club.dawdler.clientplug.web.annotation.ResponseBody;
import club.dawdler.clientplug.web.bind.RequestMethodProcessor;
import club.dawdler.clientplug.web.bind.resolver.impl.AbstractMethodArgumentResolver;
import club.dawdler.clientplug.web.classloader.RemoteClassLoaderFire;
import club.dawdler.clientplug.web.handler.AnnotationUrlHandler;
import club.dawdler.clientplug.web.handler.RequestUrlData;
import club.dawdler.clientplug.web.handler.WebValidateExecutor;
import club.dawdler.clientplug.web.interceptor.HandlerInterceptor;
import club.dawdler.clientplug.web.interceptor.InterceptorProvider;
import club.dawdler.clientplug.web.listener.WebContextListener;
import club.dawdler.clientplug.web.listener.WebContextListenerProvider;
import club.dawdler.core.annotation.Order;
import club.dawdler.core.loader.DeployClassLoader;
import club.dawdler.core.order.OrderData;
import club.dawdler.util.reflectasm.ParameterNameReader;

/**
 * @author jackson.song
 * @version V1.0
 * 客户端加载类通知类，初始化各种监听器 拦截器 controller 
 */
@Order(0)
public class WebComponentClassLoaderFire implements RemoteClassLoaderFire {
	private static final Logger logger = LoggerFactory.getLogger(WebComponentClassLoaderFire.class);

	@Override
	public void onLoadFire(Class<?> clazz, Object target) throws Throwable {
		initListener(clazz, target);
		initInterceptor(clazz, target);
		initMapping(clazz, target);
	}

	@Override
	public void onRemoveFire(Class<?> clazz) {
		removeMapping(clazz);
		InterceptorProvider.removeHandlerInterceptor(clazz);
		WebContextListenerProvider.removeWebContextListener(clazz);
	}

	@Override
	public void onRetireFire(ClassLoader classLoader) {
		releaseClassLoaderCaches(classLoader);
	}

	/**
	 * 释放web层以指定类加载器为键的静态缓存, 与WebListener.releaseClassLoaderResources共用此清单,
	 * 类加载器生命周期终结(web应用销毁或远程加载器热替换退役)时必须调用, 否则退役加载器会被静态缓存钉住无法回收;
	 * 框架级共享缓存(reflectasm方法访问器/方法参数名/kryo动态注册与池化引用)委托
	 * DeployClassLoader.releaseCaches单一清单维护, 此处只清web专属缓存.
	 */
	public static void releaseClassLoaderCaches(ClassLoader classLoader) {
		if (classLoader == null) {
			return;
		}
		AnnotationUrlHandler.removeMappings(classLoader);
		InterceptorProvider.removeHandlerInterceptors(classLoader);
		WebContextListenerProvider.removeWebContextListeners(classLoader);
		WebValidateExecutor.removeValidators(classLoader);
		RequestMethodProcessor.removeCaches(classLoader);
		AbstractMethodArgumentResolver.removeAccessibleDeclaredFields(classLoader);
		DeployClassLoader.releaseCaches(classLoader);
	}

	private void initListener(Class<?> clazz, Object target) {
		if (WebContextListener.class.isAssignableFrom(clazz)) {
			WebContextListener listener = (WebContextListener) target;
			WebContextListenerProvider.addWebContextListener(listener);
			WebContextListenerProvider.order();
		}
	}

	private void initInterceptor(Class<?> clazz, Object target) {
		if (HandlerInterceptor.class.isAssignableFrom(clazz)) {
			HandlerInterceptor interceptor = (HandlerInterceptor) target;
			List<OrderData<HandlerInterceptor>> interceptors = InterceptorProvider.getHandlerInterceptors();
			for (OrderData<HandlerInterceptor> orderData : interceptors) {
				if (orderData.getData().getClass() == clazz) {
					return;
				}
			}
			InterceptorProvider.addHandlerInterceptor(interceptor);
			InterceptorProvider.order();
		}
	}

	private void initMapping(Class<?> clazz, Object target) {
		if (clazz.isInterface()) {
			return;
		}
		if (clazz.getAnnotation(Controller.class) != null) {
			RequestMapping classRequestMapping = clazz.getAnnotation(RequestMapping.class);
			if (classRequestMapping != null && classRequestMapping.value().length > 0) {
				for (String classMapping : classRequestMapping.value()) {
					registMapping(classMapping, clazz, target);
				}
			} else {
				registMapping(null, clazz, target);
			}
		}
	}

	public void registMapping(String prefix, Class<?> clazz, Object target) {
		Method[] methods = clazz.getMethods();
		for (Method method : methods) {
			RequestMapping requestMapping = method.getAnnotation(RequestMapping.class);
			if (requestMapping != null && requestMapping.value().length > 0) {
				RequestUrlData requestUrlData = new RequestUrlData();
				method.setAccessible(true);
				requestUrlData.setMethod(method);
				requestUrlData.setRequestMapping(requestMapping);
				requestUrlData.setTarget(target);
				requestUrlData.setResponseBody(method.getAnnotation(ResponseBody.class));
				requestUrlData.setJsonIgnoreNull(method.getAnnotation(JsonIgnoreNull.class));
				requestUrlData.setHasRequestBody(hasRequestBodyParameter(method));
				for (String requestMappingPath : requestMapping.value()) {
					String mapping = prefix == null ? requestMappingPath : (prefix + requestMappingPath);
					RequestUrlData preRequestUrlData = AnnotationUrlHandler.registMapping(mapping, requestUrlData);
					if (preRequestUrlData != null) {
						logger.error("regist {} failed because the same path and method was registered at {} {}",
								mapping, preRequestUrlData.getTarget().getClass().getName(),
								preRequestUrlData.getMethod());
					}
				}
			}
		}
	}

	private boolean hasRequestBodyParameter(Method method) {
		for (Annotation[] parameterAnnotations : method.getParameterAnnotations()) {
			for (Annotation annotation : parameterAnnotations) {
				if (annotation.annotationType() == RequestBody.class) {
					return true;
				}
			}
		}
		return false;
	}

	public void removeMapping(Class<?> clazz) {
		if (clazz.getAnnotation(Controller.class) != null) {
			RequestMapping classRequestMapping = clazz.getAnnotation(RequestMapping.class);
			if (classRequestMapping != null && classRequestMapping.value().length > 0) {
				for (String classMapping : classRequestMapping.value()) {
					removeMapping(classMapping, clazz);
				}
			} else {
				removeMapping(null, clazz);
			}
			ParameterNameReader.removeParameterNames(clazz);
		}
	}

	private void removeMapping(String prefix, Class<?> clazz) {
		Method[] methods = clazz.getMethods();
		for (Method method : methods) {
			RequestMapping requestMapping = method.getAnnotation(RequestMapping.class);
			if (requestMapping != null && requestMapping.value().length > 0) {
				RequestUrlData requestUrlData = new RequestUrlData();
				requestUrlData.setMethod(method);
				requestUrlData.setRequestMapping(requestMapping);
				for (String requestMappingPath : requestMapping.value()) {
					AnnotationUrlHandler
							.removeMapping(prefix == null ? requestMappingPath : (prefix + requestMappingPath),
									requestUrlData);
				}
			}
		}
	}
}
