package com.celements.web.service;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.xwiki.component.annotation.Component;
import org.xwiki.component.annotation.Requirement;
import org.xwiki.context.Execution;
import org.xwiki.model.reference.DocumentReference;
import org.xwiki.model.reference.EntityReferenceSerializer;
import org.xwiki.script.service.ScriptService;

import com.celements.navigation.cmd.DeleteMenuItemCommand;
import com.celements.web.plugin.api.CelementsWebPluginApi;
import com.celements.web.plugin.cmd.PlainTextCommand;
import com.celements.web.sajson.Builder;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.XWikiException;

@Component("celementsweb")
public class CelementsWebScriptService implements ScriptService {

  private static final String APP_SCRIPT_XPAGE = "app";

  private static Log LOGGER = LogFactory.getFactory().getInstance(
      CelementsWebPluginApi.class);

  @Requirement
  Execution execution;

  @Requirement("local")
  EntityReferenceSerializer<String> modelSerializer;

  private XWikiContext getContext() {
    return (XWikiContext)execution.getContext().getProperty("xwikicontext");
  }

  public String getAppScriptURL(String scriptName) {
    return getAppScriptURL(scriptName, "");
  }

  public String getAppScriptURL(String scriptName, String queryString) {
    if (queryString == null) {
      queryString = "";
    }
    if (!"".equals(queryString)) {
      queryString = "&" + queryString;
    }
    return getContext().getDoc().getURL("view", "xpage=" + APP_SCRIPT_XPAGE + "&s="
        + scriptName + queryString, getContext());
  }

  public boolean isAppScriptCurrentPage(String scriptName) {
    String scriptStr = getScriptNameFromURL();
    return (!"".equals(scriptStr) && (scriptStr.equals(scriptName)));
  }

  public String getScriptNameFromURL() {
    String scriptStr = "";
    if (isAppScriptRequest()) {
      scriptStr = getAppScriptNameFromRequestURL();
    }
    return scriptStr;
  }

  public boolean isAppScriptRequest() {
    String xpageStr = getContext().getRequest().getParameter("xpage");
    return APP_SCRIPT_XPAGE.equals(xpageStr)
        && (getAppScriptNameFromRequestURL() != null);
  }

  private String getAppScriptNameFromRequestURL() {
    return getContext().getRequest().getParameter("s");
  }

  public String getCurrentPageURL(String queryString) {
    if(isAppScriptRequest()) {
      return getAppScriptURL(getScriptNameFromURL(), queryString);
    } else {
      return "?" + queryString;
    }
  }

  public String convertToPlainText(String htmlContent) {
    LOGGER.trace("convertToPlainText called on celementsweb script service for ["
        + htmlContent + "].");
    return new PlainTextCommand().convertToPlainText(htmlContent);
  }

  public Builder getNewJSONBuilder() {
    return new Builder();
  }

  public boolean deleteMenuItem(DocumentReference docRef) {
    String docFN = modelSerializer.serialize(docRef);
    try {
      if (getContext().getWiki().getRightService().hasAccessLevel("edit",
          getContext().getUser(), docFN, getContext())) {
        return new DeleteMenuItemCommand().deleteMenuItem(docRef);
      }
    } catch (XWikiException exp) {
      LOGGER.error("Failed to check 'edit' access rights for user ["
          + getContext().getUser() + "] on document [" + docFN + "]");
    }
    return false;
  }

}

@@ -25,24 +25,78 @@
 b.service;%0A%0A
+import java.util.Collections;%0Aimport java.util.List;%0A%0A
 import org.a
@@ -412,24 +412,130 @@
 Serializer;%0A
+import org.xwiki.query.Query;%0Aimport org.xwiki.query.QueryException;%0Aimport org.xwiki.query.QueryManager;%0A
 import org.x
@@ -1228,16 +1228,61 @@
 lizer;%0A%0A
+  @Requirement%0A  QueryManager queryManager;%0A%0A
   privat
@@ -3603,10 +3603,907 @@
 e;%0A  %7D%0A%0A
+  public List%3CString%5B%5D%3E getLastChangedDocuments(int numEntries) %7B%0A    return getLastChangedDocuments(numEntries, %22%22);%0A  %7D%0A%0A  //TODO write unit tests%0A  public List%3CString%5B%5D%3E getLastChangedDocuments(int numEntries, String space) %7B%0A    String xwql = %22select doc.fullName, doc.language from XWikiDocument doc%22;%0A    boolean hasSpaceRestriction = (!%22%22.equals(space));%0A    if (hasSpaceRestriction) %7B%0A      xwql = xwql + %22 where doc.space = :spaceName%22;%0A    %7D%0A    xwql = xwql + %22 order by doc.date desc%22;%0A    Query query;%0A    try %7B%0A      query = queryManager.createQuery(xwql, Query.XWQL);%0A      if (hasSpaceRestriction) %7B%0A        query = query.bindValue(%22spaceName%22, space);%0A      %7D%0A      return query.setLimit(numEntries).execute();%0A    %7D catch (QueryException exp) %7B%0A      LOGGER.error(%22Failed to create whats-new query for space %5B%22 + space + %22%5D.%22, exp);%0A    %7D%0A    return Collections.emptyList();%0A  %7D%0A%0A
 %7D%0A

add service call for getLastChangedDocuments