/*
 * Copyright 2000-2009 JetBrains s.r.o.
 *
 * 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.
 */

/*
 * @author max
 */
package com.intellij.util.messages.impl;

import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.Pair;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.messages.MessageBusConnection;
import com.intellij.util.messages.MessageHandler;
import com.intellij.util.messages.Topic;
import org.jetbrains.annotations.NotNull;

import java.lang.reflect.Method;
import java.util.List;
import java.util.Queue;

public class MessageBusConnectionImpl implements MessageBusConnection {
  private static final Logger LOG = Logger.getInstance("#com.intellij.util.messages.impl.MessageBusConnectionImpl");

  private final MessageBusImpl myBus;
  private final ThreadLocal<Queue<Message>> myPendingMessages = MessageBusImpl.createThreadLocalQueue();

  private MessageHandler myDefaultHandler;
  private final List<Pair<Topic, Object>> mySubscriptions = ContainerUtil.createLockFreeCopyOnWriteList();

  public MessageBusConnectionImpl(@NotNull MessageBusImpl bus) {
    myBus = bus;
  }

  @Override
  public <L> void subscribe(@NotNull Topic<L> topic, @NotNull L handler) throws IllegalStateException {
    mySubscriptions.add(Pair.<Topic, Object>create(topic, handler));
    if (getHandler(topic) != handler) {
      throw new IllegalStateException("Subscription to " + topic + " already exists");
    }
    myBus.notifyOnSubscription(this, topic);
  }

  @Override
  @SuppressWarnings("unchecked")
  public <L> void subscribe(@NotNull Topic<L> topic) throws IllegalStateException {
    if (myDefaultHandler == null) {
      throw new IllegalStateException("Connection must have default handler installed prior to any anonymous subscriptions. "
                                      + "Target topic: " + topic);
    }
    if (topic.getListenerClass().isInstance(myDefaultHandler)) {
      throw new IllegalStateException("Can't subscribe to the topic '" + topic +"'. Default handler has incompatible type - expected: '" +
        topic.getListenerClass() + "', actual: '" + myDefaultHandler.getClass() + "'");
    }

    subscribe(topic, (L)myDefaultHandler);
  }

  @Override
  public void setDefaultHandler(MessageHandler handler) {
    myDefaultHandler = handler;
  }

  @Override
  public void disconnect() {
    Queue<Message> jobs = myPendingMessages.get();
    myPendingMessages.remove();
    myBus.notifyConnectionTerminated(this);
    if (!jobs.isEmpty()) {
      LOG.error("Not delivered events in the queue: " + jobs);
    }
  }

  @Override
  public void dispose() {
    disconnect();
  }

  @Override
  public void deliverImmediately() {
    Queue<Message> messages = myPendingMessages.get();
    while (!messages.isEmpty()) {
      myBus.deliverSingleMessage();
    }
  }

  private Object getHandler(@NotNull Topic topic) {
    for (Pair<Topic, Object> subscription : mySubscriptions) {
      if (topic == subscription.first) return subscription.second;
    }
    return null;
  }

  void deliverMessage(@NotNull Message message) {
    final Message messageOnLocalQueue = myPendingMessages.get().poll();
    assert messageOnLocalQueue == message;

    final Topic topic = message.getTopic();
    final Object handler = getHandler(topic);

    try {
      Method listenerMethod = message.getListenerMethod();

      if (handler == myDefaultHandler) {
        myDefaultHandler.handle(listenerMethod, message.getArgs());
      }
      else {
        listenerMethod.invoke(handler, message.getArgs());
      }
    }
    catch (AbstractMethodError e) {
      //Do nothing. This listener just does not implement something newly added yet.
    }
    catch(Throwable e) {
      LOG.error(e.getCause() == null ? e : e.getCause());
    }
  }

  void scheduleMessageDelivery(Message message) {
    myPendingMessages.get().offer(message);
  }

  public String toString() {
    return mySubscriptions.toString();
  }
}

@@ -730,76 +730,22 @@
 lij.
-openapi.util.Pair;%0Aimport com.intellij.util.containers.ContainerUtil
+util.SmartFMap
 ;%0Aim
@@ -969,31 +969,8 @@
 od;%0A
-import java.util.List;%0A
 impo
@@ -1218,16 +1218,58 @@
  myBus;%0A
+  @SuppressWarnings(%22SSBasedInspection%22) %0A
   privat
@@ -1423,23 +1423,26 @@
 ate 
-final List%3CPair
+volatile SmartFMap
 %3CTop
@@ -1452,17 +1452,16 @@
  Object%3E
-%3E
  mySubsc
@@ -1475,51 +1475,26 @@
 s = 
-ContainerUtil.createLockFreeCopyOnWriteList
+SmartFMap.emptyMap
 ();%0A
@@ -1705,91 +1705,72 @@
     
-mySubscriptions.add(Pair.%3CTopic, Object%3Ecreate(topic, handler));
+synchronized (myPendingMessages) %7B
 %0A    
+  
 if (
-getHandler
+mySubscriptions.get
 (top
@@ -1776,27 +1776,26 @@
 pic) != 
-handler
+null
 ) %7B%0A
+  
       th
@@ -1869,24 +1869,94 @@
 y exists%22);%0A
+      %7D%0A      mySubscriptions = mySubscriptions.plus(topic, handler);%0A
     %7D%0A    my
@@ -3336,218 +3336,8 @@
  %7D%0A%0A
-  private Object getHandler(@NotNull Topic topic) %7B%0A    for (Pair%3CTopic, Object%3E subscription : mySubscriptions) %7B%0A      if (topic == subscription.first) return subscription.second;%0A    %7D%0A    return null;%0A  %7D%0A%0A
   vo
@@ -3573,18 +3573,27 @@
 r = 
-getHandler
+mySubscriptions.get
 (top

save some memory on message bus connections