package com.celements.lastChanged;

import java.util.Arrays;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xwiki.bridge.event.DocumentCreatedEvent;
import org.xwiki.bridge.event.DocumentDeletedEvent;
import org.xwiki.bridge.event.DocumentUpdatedEvent;
import org.xwiki.component.annotation.Component;
import org.xwiki.component.annotation.Requirement;
import org.xwiki.model.reference.DocumentReference;
import org.xwiki.observation.EventListener;
import org.xwiki.observation.event.Event;

@Component("lastChange-DocumentChangesListener")
public class DocumentChangesListener implements EventListener {

  private static Logger _LOGGER  = LoggerFactory.getLogger(DocumentChangesListener.class);

  @Requirement
  ILastChangedRole lastChangedSrv;

  @Override
  public String getName() {
    return "lastChange-DocumentChangesListener";
  }

  @Override
  public List<Event> getEvents() {
    return Arrays.<Event>asList(new DocumentCreatedEvent(), new DocumentUpdatedEvent(),
        new DocumentDeletedEvent());
  }

  @Override
  public void onEvent(Event event, Object source, Object data) {
    if ((source != null) && (source instanceof DocumentReference)) {
      DocumentReference docRef = (DocumentReference) source;
      ((LastChangedService)lastChangedSrv).invalidateCacheForSpaceRef(
          docRef.getLastSpaceReference());
    } else {
      _LOGGER.error("onEvent failed docref '{}'", source);
    }
  }

}

@@ -530,16 +530,57 @@
 Event;%0A%0A
+import com.xpn.xwiki.doc.XWikiDocument;%0A%0A
 @Compone
@@ -1223,24 +1223,29 @@
 tanceof 
+XWiki
 Document
 Referenc
@@ -1240,21 +1240,62 @@
 ment
-Reference)) %7B
+)) %7B%0A      XWikiDocument doc = (XWikiDocument) source;
 %0A   
@@ -1324,17 +1324,23 @@
 ocRef = 
-(
+doc.get
 Document
@@ -1348,24 +1348,18 @@
 eference
+(
 )
- source
 ;%0A      

fix onEvent in DocumentChangesListener