/**
 * Copyright 2015 DuraSpace, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.fcrepo.jms.headers;

import static org.fcrepo.kernel.RdfLexicon.REPOSITORY_NAMESPACE;
import static org.modeshape.jcr.api.JcrConstants.JCR_CONTENT;
import static org.slf4j.LoggerFactory.getLogger;

import java.io.IOException;
import java.util.Set;

import javax.jms.JMSException;
import javax.jms.Message;

import org.apache.commons.lang.StringUtils;
import org.fcrepo.jms.observer.JMSEventMessageFactory;
import org.fcrepo.kernel.observer.FedoraEvent;
import org.fcrepo.kernel.utils.EventType;
import org.slf4j.Logger;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.collect.Iterables;

/**
 * Generates JMS {@link Message}s composed entirely of headers, based entirely
 * on information found in the {@link FedoraEvent} that triggers publication.
 *
 * @author ajs6f
 * @author escowles
 * @since Dec 2, 2013
 */
public class DefaultMessageFactory implements JMSEventMessageFactory {

    public static final String JMS_NAMESPACE = "org.fcrepo.jms.";

    public static final String TIMESTAMP_HEADER_NAME = JMS_NAMESPACE
            + "timestamp";

    public static final String IDENTIFIER_HEADER_NAME = JMS_NAMESPACE
            + "identifier";

    public static final String EVENT_TYPE_HEADER_NAME = JMS_NAMESPACE
            + "eventType";

    public static final String BASE_URL_HEADER_NAME = JMS_NAMESPACE
            + "baseURL";

    public static final String PROPERTIES_HEADER_NAME = JMS_NAMESPACE
            + "properties";

    public static final String USER_HEADER_NAME = JMS_NAMESPACE + "user";
    public static final String USER_AGENT_HEADER_NAME = JMS_NAMESPACE + "userAgent";

    private String baseURL;
    private String userAgent;

    @Override
    public Message getMessage(final FedoraEvent jcrEvent,
        final javax.jms.Session jmsSession) throws JMSException {

        final Message message = jmsSession.createMessage();
        message.setLongProperty(TIMESTAMP_HEADER_NAME, jcrEvent.getDate());
        String path = jcrEvent.getPath();
        if ( path.endsWith("/" + JCR_CONTENT) ) {
            path = path.replaceAll("/" + JCR_CONTENT,"");
        }

        // extract baseURL and userAgent from event UserData
        try {
            final String userdata = jcrEvent.getUserData();
            if (!StringUtils.isBlank(userdata)) {
                final ObjectMapper mapper = new ObjectMapper();
                final JsonNode json = mapper.readTree(userdata);
                String url = json.get("baseURL").asText();
                while (url.endsWith("/")) {
                    url = url.substring(0, url.length() - 1);
                }
                this.baseURL = url;
                this.userAgent = json.get("userAgent").asText();
                LOGGER.debug("MessageFactory baseURL: {}, userAgent: {}", baseURL, userAgent);

            } else {
                LOGGER.warn("MessageFactory event UserData is empty!");
            }

        } catch ( final IOException ex ) {
            LOGGER.warn("Error setting baseURL or userAgent", ex);
        }

        message.setStringProperty(IDENTIFIER_HEADER_NAME, path);
        message.setStringProperty(EVENT_TYPE_HEADER_NAME, getEventURIs( jcrEvent
                .getTypes()));
        message.setStringProperty(BASE_URL_HEADER_NAME, baseURL);
        message.setStringProperty(USER_HEADER_NAME, jcrEvent.getUserID());
        message.setStringProperty(USER_AGENT_HEADER_NAME, userAgent);
        message.setStringProperty(PROPERTIES_HEADER_NAME, Joiner.on(',').join(jcrEvent.getProperties()));

        LOGGER.trace("getMessage() returning: {}", message);
        return message;
    }

    private static String getEventURIs(final Set<Integer> types) {
        final String uris = Joiner.on(',').join(Iterables.transform(types, new Function<Integer, String>() {

            @Override
            public String apply(final Integer type) {
                return REPOSITORY_NAMESPACE + EventType.valueOf(type);
            }
        }));
        LOGGER.debug("Constructed event type URIs: {}", uris);
        return uris;
    }

    private static final Logger LOGGER = getLogger(DefaultMessageFactory.class);

}

@@ -852,16 +852,52 @@
 til.Set;
+%0Aimport java.util.stream.Collectors;
 %0A%0Aimport
@@ -1265,130 +1265,8 @@
 ode;
-%0Aimport com.google.common.base.Function;%0Aimport com.google.common.base.Joiner;%0Aimport com.google.common.collect.Iterables;
 %0A%0A/*
@@ -4140,36 +4140,33 @@
 R_NAME, 
-Joiner.on(',')
+String
 .join(
+%22,%22, 
 jcrEvent
@@ -4377,89 +4377,22 @@
 s = 
-Joiner.on(',').join(Iterabl
+typ
 es.
+s
 tr
-ansform(types, new Function%3CInteger, String%3E() %7B%0A
+eam()
 %0A   
@@ -4396,34 +4396,24 @@
             
-@Override%0A
             
@@ -4416,72 +4416,26 @@
     
-public String apply(final Integer type) %7B%0A                return
+         .map(x -%3E
  REP
@@ -4476,15 +4476,23 @@
 eOf(
-type);%0A
+x))%0A           
     
@@ -4499,26 +4499,26 @@
         
-%7D%0A
+  
         
 %7D));%0A   
@@ -4513,13 +4513,44 @@
     
-%7D
+.collect(Collectors.joining(%22,%22
 ));%0A
+%0A
     

remove guava Iterables for a java8 stream