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

import java.io.IOException;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import ru.bitel.bgbilling.kernel.container.managed.ServerContext;
import ru.bitel.bgbilling.modules.tv.server.handler.HttpHandler;
import ru.bitel.bgbilling.server.util.Setup;

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

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

            final String[] path = getPath( request );
            final int moduleId = getModuleId( path, 2 );

			final String resource = path.length >= 5 ? path[4] : 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 );
			}
		}
	}
}
