package ru.bitel.bgbilling.modules.tv.dyn.tv24h;

import org.apache.log4j.Logger;
import ru.bitel.bgbilling.kernel.container.managed.ServerContext;
import ru.bitel.bgbilling.modules.tv.access.om.HttpHandler;
import ru.bitel.bgbilling.server.util.Setup;
import ru.bitel.common.Utils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.regex.Pattern;

public class Tv24hWebhookHandler
	implements HttpHandler
{
	private static final Logger logger = Logger.getLogger( Tv24hWebhookHandler.class );

	private static final Pattern patternSlash = Pattern.compile( "/" );

	@Override
	public void handle( HttpServletRequest request, HttpServletResponse response )
	{
		try
		{
			request.setCharacterEncoding( "UTF-8" );
			response.setCharacterEncoding( "UTF-8" );

			final String[] path = patternSlash.split( request.getPathInfo() );
			final int moduleId = Utils.parseInt( path[2] );

			final String resource;

			if( path.length >= 5 )
			{
				resource = path[4];
			}
			else
			{
				resource = null;
			}

			ServerContext context = new ServerContext( Setup.getSetup(), moduleId, 0 );
			ServerContext.push( context );
			try
			{
				final Tv24hConf conf = context.getSetup().getConfig( context.getModuleId(), Tv24hConf.class );

				final Tv24hWebhookService service = new Tv24hWebhookService( context, conf, path, resource, request, response );

				response.setHeader( "Content-Type", "application/json" );

				service.handle();

				response.setStatus( HttpServletResponse.SC_OK );

				response.flushBuffer();

				context.commit();
			}
			finally
			{
				context.recycle();
				ServerContext.pop( context, null );
			}
		}
		catch( Exception ex )
		{
			logger.error( ex.getMessage(), ex );

			try
			{
				response.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR );
			}
			catch( IOException e )
			{
				logger.error( ex.getMessage(), ex );
			}
		}
	}
}
