package com.apobates.forum.core.ad;

import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.apobates.forum.core.entity.Board;
import com.apobates.forum.core.entity.Topic;
import com.apobates.forum.utils.Commons;

/**
 * 抽像的连接器工厂
 * 
 * @author xiaofanku
 * @since 20191105
 * @param <T>
 */
public class ActiveDirectoryConnectorFactory {
	
	public static Optional<Topic> parseRefererToTopic(String requestRefString, String siteDomain){
		if (requestRefString == null || !requestRefString.startsWith(siteDomain)) { // 只允许本站连接
			return Optional.empty();
		}
		//
		Pattern pattern = Pattern.compile("/topic/(.*).xhtml");
		Matcher m = pattern.matcher(requestRefString);
		String connectValue = null;
		if (m.find()) {
			connectValue = m.group(1);
		}
		try{
			return build(Topic.class, connectValue);
		}catch(Exception e){
			return Optional.empty();
		}
	}
	
	public static Optional<Board> parseRefererToBoard(String requestRefString, String siteDomain){
		if (requestRefString == null || !requestRefString.startsWith(siteDomain)) { // 只允许本站连接
			return Optional.empty();
		}
		//
		Pattern pattern = Pattern.compile("/board/(.*).xhtml");
		Matcher m = pattern.matcher(requestRefString);
		String connectValue = null;
		if (m.find()) {
			connectValue = m.group(1);
		}
		try{
			if(connectValue != null && connectValue.contains("volumes/")){ //从版块组->版块
				connectValue = connectValue.replace("volumes/", "");
			}
		}catch(NullPointerException e){}
		try{
			return build(Board.class, connectValue);
		}catch(Exception e){
			return Optional.empty();
		}
	}
	/**
	 * 
	 * @param boardGroupId 
	 * @param boardId
	 * @param topicId
	 * @return
	 */
	public static String generateConnectString(int boardGroupId, long boardId, long topicId){
		Topic tr = new Topic();
		tr.setId(topicId);
		tr.setBoardId(boardId);
		tr.setVolumesId(boardGroupId);

		return tr.getConnect();
	}
	public static String generateBoardConnectString(int boardGroupId, long boardId){
		Board b = new Board();
		b.setId(boardId);
		b.setVolumesId(boardGroupId);

		return b.getConnect();
	}
	public static <T> Optional<T> build(Class<T> resultClass, String connectValue)throws IllegalStateException{
		if(!ActiveDirectoryConnector.class.isAssignableFrom(resultClass)){
			throw new IllegalStateException("参数:resultClass,没有实现ActiveDirectoryConnector接口");
		}
		if(!Commons.isNotBlank(connectValue)){
			return Optional.empty();
		}
		
		try{
			@SuppressWarnings("unchecked")
			ActiveDirectoryConnector<T> adc = (ActiveDirectoryConnector<T>)resultClass.newInstance();
			return adc.toConnector(connectValue);
		}catch(InstantiationException e){
			throw new IllegalStateException(e);
		}catch(IllegalAccessException e){
			throw new IllegalStateException(e);
		}
	}
}
