package ca.firstvoices.nuxeo.operations;

import java.io.Serializable;
import java.util.Iterator;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.nuxeo.ecm.automation.AutomationService;
import org.nuxeo.ecm.automation.core.Constants;
import org.nuxeo.ecm.automation.core.annotations.Context;
import org.nuxeo.ecm.automation.core.annotations.Operation;
import org.nuxeo.ecm.automation.core.annotations.OperationMethod;
import org.nuxeo.ecm.automation.core.annotations.Param;
import org.nuxeo.ecm.core.api.Blob;
import org.nuxeo.ecm.core.api.Blobs;
import org.nuxeo.ecm.core.api.CoreSession;
import org.nuxeo.ecm.core.api.DocumentModelList;
import org.nuxeo.ecm.core.api.IterableQueryResult;
import org.nuxeo.ecm.core.api.UnrestrictedSessionRunner;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;

@Operation(id = ListDialects.ID, category = Constants.CAT_DOCUMENT, label = "List dialects in FV tree", description = "Returns a list of dialects based on selection criteria")
public class ListDialects {
    public static final String ID = "Document.ListDialects";

    private static Log log = LogFactory.getLog(ListDialects.class);

    public static final String ALL_DIALECTS = "*";

    public static final String DIALECTS_TO_JOIN = "to-join";

    public static final String NEW_DIALECTS = "new";

    public static final String ENABLED_DIALECTS = "enabled";

    public static final String DISABLED_DIALECTS = "disabled";

    public static final String PUBLISHED_DIALECTS = "published";

    @Context
    protected AutomationService automationService;

    @Context
    protected CoreSession session;

    @Param(name = "dialectState", required = false, values = { DIALECTS_TO_JOIN, ALL_DIALECTS, NEW_DIALECTS,
            ENABLED_DIALECTS, DISABLED_DIALECTS, PUBLISHED_DIALECTS })
    protected String dialectState = DIALECTS_TO_JOIN;

    @OperationMethod
    public Blob run() throws Exception {
        DocumentModelList dList = null;

        String queryFront = "SELECT ecm:uuid, dc:title FROM FVDialect WHERE ";
        String queryVersion = "ecm:isVersion=0 ";
        String queryProxy = "ecm:isProxy=0 AND ";
        String querySort = "ORDER BY dc:title ASC";
        String query = queryFront + queryVersion + querySort;

        switch (dialectState.toLowerCase()) {
        case ALL_DIALECTS:
            query = "SELECT ecm:uuid, dc:title, ecm:currentLifeCycleState FROM FVDialect " + querySort;
            break;
        case NEW_DIALECTS:
            query = queryFront + "ecm:currentLifeCycleState = 'New' " + querySort;
            break;
        case DIALECTS_TO_JOIN:
            query = queryFront
                    + "(ecm:currentLifeCycleState = 'Enabled' OR  (ecm:currentLifeCycleState = 'Published' AND ecm:isProxy=0)) AND "
                    + queryVersion + querySort;
            break;
        case ENABLED_DIALECTS:
            query = queryFront + "ecm:currentLifeCycleState = 'Enabled' AND " + queryVersion + querySort;
            break;
        case DISABLED_DIALECTS:
            query = queryFront + "ecm:currentLifeCycleState = 'Disabled' AND " + queryVersion + querySort;
            break;
        case PUBLISHED_DIALECTS:
            query = queryFront + "ecm:currentLifeCycleState = 'Published' AND " + queryProxy + queryVersion + querySort;
            break;
        }

        UnrestrictedDialectQuery dialectListQueryRunner = new UnrestrictedDialectQuery(session, query);
        dialectListQueryRunner.runUnrestricted();

        return Blobs.createJSONBlobFromValue(dialectListQueryRunner.resultSetArray);
    }

    protected static class UnrestrictedDialectQuery extends UnrestrictedSessionRunner {

        private String query;

        private ArrayNode resultSetArray;

        protected ObjectMapper mapper;

        private IterableQueryResult result;

        protected UnrestrictedDialectQuery(CoreSession session, String query) {
            super(session);
            this.query = query;
        }

        @Override
        public void run() {
            try {
                result = session.queryAndFetch(query, "NXQL");
                Iterator<Map<String, Serializable>> it = result.iterator();

                mapper = new ObjectMapper();
                resultSetArray = mapper.createArrayNode();

                while (it.hasNext()) {
                    Map<String, Serializable> item = it.next();
                    // JSONObject object = new JSONObject();
                    // object.accumulateAll(item);
                    resultSetArray.add(mapper.writeValueAsString(item));
                }
            } catch (JsonProcessingException e) {
                log.error(e);
            } finally {
                result.close();
            }

        }
    }
}
@@ -81,24 +81,75 @@
 va.util.
-Iterator
+ArrayList;%0Aimport java.util.Iterator;%0Aimport java.util.List
 ;%0Aimport
@@ -867,174 +867,8 @@
 r;%0A%0A
-import com.fasterxml.jackson.core.JsonProcessingException;%0Aimport com.fasterxml.jackson.databind.ObjectMapper;%0Aimport com.fasterxml.jackson.databind.node.ArrayNode;%0A%0A
 @Ope
@@ -3618,24 +3618,17 @@
 r.result
-SetArray
+s
 );%0A    %7D
@@ -3769,117 +3769,94 @@
 ate 
-ArrayNode resultSetArray;%0A%0A        protected ObjectMapper mapper;%0A%0A        private IterableQueryResult result
+IterableQueryResult result;%0A%0A        protected List%3CMap%3CString, Serializable%3E%3E results
 ;%0A%0A 
@@ -4065,24 +4065,69 @@
       try %7B%0A
+                results = new ArrayList%3C%3E();%0A
             
@@ -4258,113 +4258,8 @@
 );%0A%0A
-                mapper = new ObjectMapper();%0A                resultSetArray = mapper.createArrayNode();%0A%0A
     
@@ -4381,171 +4381,25 @@
     
-// JSONObject object = new JSONObject();%0A                    // object.accumulateAll(item);%0A                    resultSetArray.add(mapper.writeValueAsString
+results.add
 (item)
-)
 ;%0A  
@@ -4418,88 +4418,8 @@
   %7D%0A
-            %7D catch (JsonProcessingException e) %7B%0A                log.error(e);%0A
     

fix operation to return json