package org.lantern.state;

import java.util.ArrayList;

import org.lantern.Roster;
import org.lantern.XmppHandler;
import org.lantern.event.Events;
import org.lastbamboo.common.p2p.P2PConnectionEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.eventbus.Subscribe;
import com.google.inject.Inject;

public class InviteQueue {
    private static final Logger LOG = LoggerFactory
            .getLogger(InviteQueue.class);

    private final XmppHandler xmppHandler;
    private final Model model;

    private final Roster roster;

    @Inject
    public InviteQueue(final XmppHandler handler, final Model model,
            final Roster roster) {
        this.xmppHandler = handler;
        this.model = model;
        this.roster = roster;
        Events.register(this);
    }

    @Subscribe
    public void onP2PConnectionEvent(P2PConnectionEvent e) {
        if (e.isConnected()) {
            // resend invites
            Friends friends = model.getFriends();
            ArrayList<String> pendingInvites = new ArrayList<String>(
                    model.getPendingInvites());
            for (String email : pendingInvites) {
                LOG.info("Resending pending invite to {}", email);
                Friend friend = friends.get(email);
                xmppHandler.sendInvite(friend, true);
            }
        }

    }

    public void invite(Friend friend) {
        String email = friend.getEmail();
        if (xmppHandler.sendInvite(friend, false)) {
            // we need to mark this email as pending, in case
            // our invite gets lost.
            model.addPendingInvite(email);
        }

        Events.sync(SyncPath.FRIENDS, model.getFriends().getFriends());

    }

}

@@ -54,35 +54,8 @@
 t;%0A%0A
-import org.lantern.Roster;%0A
 impo
@@ -364,19 +364,19 @@
  Logger 
-LOG
+log
  = Logge
@@ -507,42 +507,8 @@
 l;%0A%0A
-    private final Roster roster;%0A%0A
     
@@ -586,41 +586,8 @@
 odel
-,%0A            final Roster roster
 ) %7B%0A
@@ -654,38 +654,8 @@
 el;%0A
-        this.roster = roster;%0A
     
@@ -1063,11 +1063,11 @@
     
-LOG
+log
 .inf
@@ -1326,24 +1326,42 @@
 getEmail();%0A
+        try %7B%0A    
         if (
@@ -1397,24 +1397,28 @@
 , false)) %7B%0A
+    
             
@@ -1479,16 +1479,20 @@
         
+    
 // our i
@@ -1508,16 +1508,162 @@
 s lost.%0A
+                model.addPendingInvite(email);%0A            %7D%0A        %7D catch (Exception e) %7B%0A            log.debug(%22failed to send invite: %22, e);%0A
         
@@ -1703,25 +1703,24 @@
 ;%0A        %7D%0A
-%0A
         Even

handle exception on sending invite (usually caused by being disconnected from server)