package com.nagarro.server;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;

import com.isomorphic.datasource.DSRequest;
import com.isomorphic.rpc.RPCManager;
import com.isomorphic.rpc.RPCRequest;
import com.isomorphic.servlet.RequestContext;

/**
 * Adds Spring transaction support to SmartGWT processing.
 *
 * @see <a href= "https://www.smartclient.com/smartgwt/javadoc/com/smartgwt/client/docs/SpringIntegration.html">
 *      https://www.smartclient.com/smartgwt/javadoc/com/smartgwt/client/docs/SpringIntegration.html</a>.
 */
public class IDACallWithErrorsAndTransactions extends IDACallWithErrors {

    private static final long serialVersionUID = 278680417375486561L;

    private static final Logger LOGGER = LoggerFactory.getLogger(IDACallWithErrorsAndTransactions.class);

    @Autowired
    private SpringSmartGWTService springSmartGWTService;

    @Override
    public void init(final ServletConfig servletConfig) throws ServletException {
        super.init(servletConfig);

        // autowire the SpringSmartGWTService
        SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, servletConfig.getServletContext());
    }

    @Override
    public void processRPCTransaction(final RPCManager rpc, final RequestContext context) throws Exception {
        // process queue with our transactional service
        rpc.getRequests().forEach(baseRequest -> {
            if (baseRequest instanceof DSRequest) {
                LOGGER.info("DSRequest: {}, Operation: {}, OperationId: {}, Component: {}", ((DSRequest) baseRequest).getDataSourceName(),
                        ((DSRequest) baseRequest).getOperationType(), ((DSRequest) baseRequest).getOperationId(), ((DSRequest) baseRequest).getComponentId());
            } else if (baseRequest instanceof RPCRequest) {
                LOGGER.info("RPCRequest: {}/{}, Method: {}", ((RPCRequest) baseRequest).getAppID(), ((RPCRequest) baseRequest).getServerObjectID(),
                        ((RPCRequest) baseRequest).getMethodName());
            }
        });
        springSmartGWTService.processQueue(rpc);
    }

}
