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

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 WinkHandler
    implements HttpHandler
{
    private final Logger logger = LogManager.getLogger();

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

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

                final WinkService service = new WinkService( context, conf, request.getPathInfo(), 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 );
            }
        }
    }
}