package net.sf.jabref.gui.maintable;

import net.sf.jabref.model.database.event.EntryAddedEvent;
import net.sf.jabref.model.database.event.EntryRemovedEvent;
import net.sf.jabref.model.entry.BibEntry;
import net.sf.jabref.model.entry.event.EntryChangedEvent;

import ca.odell.glazedlists.EventList;
import com.google.common.eventbus.Subscribe;

public class ListSynchronizer {

    private final EventList<BibEntry> list;

    public ListSynchronizer(EventList<BibEntry> list) {
        this.list = list;
    }

    @Subscribe
    public void listen(EntryAddedEvent entryAddedEvent) {
        lock();
        try {
            list.add(entryAddedEvent.getBibEntry());
        } finally {
            unlock();
        }
    }

    @Subscribe
    public void listen(EntryRemovedEvent entryRemovedEvent) {
        lock();
        try {
            list.remove(entryRemovedEvent.getBibEntry());
        } finally {
            unlock();
        }
    }

    @Subscribe
    public void listen(EntryChangedEvent entryChangedEvent) {
        lock();
        try {
            int index = list.indexOf(entryChangedEvent.getBibEntry());
            if (index != -1) {
                // SpecialFieldUtils.syncSpecialFieldsFromKeywords update an entry during
                // DatabaseChangeEvent.ADDED_ENTRY
                // thus,
                list.set(index, entryChangedEvent.getBibEntry());
            }
        } finally {
            unlock();
        }
    }

    private void lock() {
        list.getReadWriteLock().writeLock().lock();
    }

    private void unlock() {
        list.getReadWriteLock().writeLock().unlock();
    }
}

@@ -1067,66 +1067,78 @@
     
-int index =
+// cannot use
  list
-.
+#
 indexOf
-(entryChangedEvent.getBibEntry());
+ b/c it won't distinguish between duplicates
 %0A   
@@ -1150,193 +1150,122 @@
     
-i
 f
+or
  (in
-dex != -1) %7B%0A                // SpecialFieldUtils.syncSpecialFieldsFromKeywords update an entry during%0A                // Database
+t i = 0; i %3C list.size(); i++) %7B%0A                if (list.get(i) == entry
 Change
+d
 Event.
-ADDED_ENTRY%0A                // thus,%0A
+getBibEntry()) %7B%0A    
     
@@ -1286,20 +1286,16 @@
 st.set(i
-ndex
 , entryC
@@ -1314,32 +1314,77 @@
 getBibEntry());%0A
+                    break;%0A                %7D%0A
             %7D%0A  

Fix main table bug when creating a duplicate (#2135)