package com.oath.micro.server.servers.grizzly;

import java.util.List;

import com.oath.cyclops.types.persistent.PersistentList;
import com.oath.micro.server.module.MicroserverEnvironment;
import lombok.AllArgsConstructor;


import org.springframework.context.ApplicationContext;

import com.oath.micro.server.module.Module;
import com.oath.micro.server.module.ModuleDataExtractor;
import com.oath.micro.server.servers.ServerApplication;
import com.oath.micro.server.servers.ServerApplicationFactory;
import com.oath.micro.server.servers.model.AllData;
import com.oath.micro.server.servers.model.FilterData;
import com.oath.micro.server.servers.model.ServerData;
import com.oath.micro.server.servers.model.ServletData;

@AllArgsConstructor
public class GrizzlyApplicationFactory implements ServerApplicationFactory {

	
	
	
	public ServerApplication createApp(final  Module module, final ApplicationContext rootContext) {
		 ModuleDataExtractor extractor = new ModuleDataExtractor(module);
		PersistentList resources = extractor.getRestResources(rootContext);

		MicroserverEnvironment microserverEnvironment = rootContext.getBean(MicroserverEnvironment.class);

		microserverEnvironment.assureModule(module);
		String fullRestResource = "/" + module.getContext() + "/*";

		ServerData serverData = new ServerData(microserverEnvironment.getModuleBean(module).getPort(),
				resources,
				rootContext, fullRestResource, module);
		List<FilterData> filterDataList = extractor.createFilteredDataList(serverData);
		List<ServletData> servletDataList = extractor.createServletDataList(serverData);

		GrizzlyApplication app = new GrizzlyApplication(
				new AllData(serverData,
							filterDataList,
							servletDataList,
							module.getListeners(serverData),
							module.getRequestListeners(serverData)));
		return app;
	}
}
