/*
 * Copyright (c) 2005 - 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy
 * of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed
 * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
 * CONDITIONS OF ANY KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations under the License.
 */
package org.wso2.carbon.event.input.adapter.wso2event.internal.ds;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.osgi.service.component.ComponentContext;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.databridge.commons.Credentials;
import org.wso2.carbon.databridge.commons.Event;
import org.wso2.carbon.databridge.commons.StreamDefinition;
import org.wso2.carbon.databridge.core.AgentCallback;
import org.wso2.carbon.databridge.core.DataBridgeSubscriberService;
import org.wso2.carbon.event.input.adapter.core.InputEventAdapterFactory;
import org.wso2.carbon.event.input.adapter.wso2event.WSO2EventAdapter;
import org.wso2.carbon.event.input.adapter.wso2event.WSO2EventEventAdapterFactory;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;


/**
 * @scr.component name="input.wso2EventAdapterService.component" immediate="true"
 * @scr.reference name="agentserverservice.service"
 * interface="org.wso2.carbon.databridge.core.DataBridgeSubscriberService" cardinality="1..1"
 * policy="dynamic" bind="setDataBridgeSubscriberService" unbind="unSetDataBridgeSubscriberService"
 */


public class WSO2EventAdapterServiceDS {

    private static final Log log = LogFactory.getLog(WSO2EventAdapterServiceDS.class);

    /**
     * initialize the agent service here service here.
     *
     * @param context
     */


    protected void activate(ComponentContext context) {

        try {
            InputEventAdapterFactory wso2EventEventAdapterFactory = new WSO2EventEventAdapterFactory();
            context.getBundleContext().registerService(InputEventAdapterFactory.class.getName(), wso2EventEventAdapterFactory, null);
            if (log.isDebugEnabled()) {
                log.debug("Successfully deployed the input WSO2Event adapter service");
            }
        } catch (RuntimeException e) {
            log.error("Can not create the input WSO2Event adapter service ", e);
        }
    }

    protected void setDataBridgeSubscriberService(
            DataBridgeSubscriberService dataBridgeSubscriberService) {
        if (WSO2EventAdapterServiceValueHolder.getDataBridgeSubscriberService() == null) {
            WSO2EventAdapterServiceValueHolder.registerDataBridgeSubscriberService(dataBridgeSubscriberService);

            dataBridgeSubscriberService.subscribe(new AgentCallback() {
                @Override
                public void definedStream(StreamDefinition streamDefinition, int i) {

                }

                @Override
                public void removeStream(StreamDefinition streamDefinition, int i) {

                }

                @Override
                public void receive(List<Event> events, Credentials credentials) {
                    try {
                        PrivilegedCarbonContext.startTenantFlow();
                        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(credentials.getTenantId());
                        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(credentials.getDomainName());

                        String currentStreamId = null;
                        int lastProcessedIndex = 0;
                        int currentIndex = 0;
                        for (Event event : events) {
                            currentIndex++;
                            if (currentStreamId == null) {
                                currentStreamId = event.getStreamId();
                            } else if (!currentStreamId.equalsIgnoreCase(event.getStreamId())) {
                                pushToAdapter(currentStreamId, credentials.getDomainName(),
                                        events.subList(lastProcessedIndex, currentIndex));
                                lastProcessedIndex = currentIndex - 1;
                                currentStreamId = event.getStreamId();
                            } else if (currentIndex == events.size()) {
                                pushToAdapter(currentStreamId, credentials.getDomainName(),
                                        events.subList(lastProcessedIndex, currentIndex));
                            }
                        }
                    } finally {
                        PrivilegedCarbonContext.endTenantFlow();
                    }
                }

                private void pushToAdapter(String streamId, String tenantDomain, List<Event> events) {
                    WSO2EventAdapter adapter = WSO2EventAdapterServiceValueHolder.getAdapterService(tenantDomain, streamId);
                    if (adapter != null) {
                        adapter.getEventAdaptorListener().onEvent(events);
                    }
                    if (log.isDebugEnabled()) {
                        log.debug("Event received in wso2Event Adapter - " + events);
                    }
                }
            });
        }
    }

    protected void unSetDataBridgeSubscriberService(
            DataBridgeSubscriberService dataBridgeSubscriberService) {

    }

}

@@ -3751,1063 +3751,468 @@
 ));%0A
-%0A                        String currentStreamId = null;%0A                        int lastProcessedIndex = 0;%0A                        int currentIndex = 0;%0A                        for (Event event : events) %7B%0A                            currentIndex++;%0A                            if (currentStreamId == null) %7B%0A                                currentStreamId = event.getStreamId();%0A                            %7D else if (!currentStreamId.equalsIgnoreCase(event.getStreamId())) %7B%0A                                pushToAdapter(currentStreamId, credentials.getDomainName(),%0A                                        events.subList(lastProcessedIndex, currentIndex));%0A                                lastProcessedIndex = currentIndex - 1;%0A                                currentStreamId = event.getStreamId();%0A                            %7D else if (currentIndex == events.size()) %7B%0A                                pushToAdapter(currentStreamId, credentials.getDomainName(),%0A                                        events.subList(lastProcessedIndex, currentIndex)
+                        for (Event event : events) %7B%0A                            ConcurrentHashMap%3CString, WSO2EventAdapter%3E adapters = WSO2EventAdapterServiceValueHolder.getAdapterService(credentials.getDomainName(), event.getStreamId());%0A                            if (adapters != null) %7B%0A                                for (WSO2EventAdapter adapter : adapters.values()) %7B%0A                                    adapter.getEventAdaptorListener().onEvent(event
 );%0A 
@@ -4230,34 +4230,42 @@
                 
-%7D%0A
+    %7D%0A    
                 
@@ -4298,106 +4298,43 @@
     
-%7D finally %7B%0A                        PrivilegedCarbonContext.endTenantFlow();%0A                    %7D
+        if (log.isDebugEnabled()) %7B
 %0A   
@@ -4338,35 +4338,32 @@
                 
-%7D%0A%0A
                 
@@ -4366,132 +4366,55 @@
     
-private void pushToAdapter(String streamId, String tenantDomain, List%3CEvent%3E events) %7B%0A                    WSO
+log.debug(%22Event received in wso
 2Event
+ 
 Adapter 
 adap
@@ -4413,214 +4413,56 @@
 ter 
-adapter = WSO2EventAdapterServiceValueHolder.getAdapterService(tenantDomain, streamId);%0A                    if (adapter != null) %7B%0A                        adapter.getEventAdaptorListener().onEvent(events);%0A
+- %22 + event);%0A                            %7D%0A    
     
@@ -4503,33 +4503,17 @@
     
-if (log.isDebugEnabled())
+%7D finally
  %7B%0A 
@@ -4539,67 +4539,46 @@
     
-log.debug(%22Event received in wso2Event Adapter - %22 + events
+PrivilegedCarbonContext.endTenantFlow(
 );%0A 

Revert the change done to WSO2EventAdapterService.