/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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.
 */

/*
 * Camel Api Route test generated by camel-component-util-maven-plugin
 * Generated on: Tue Jun 24 22:42:08 PDT 2014
 */
package org.apache.camel.component.box;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import com.box.boxjavalibv2.dao.BoxEvent;
import com.box.boxjavalibv2.dao.BoxFile;
import com.box.boxjavalibv2.requests.requestobjects.BoxItemCopyRequestObject;
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.box.internal.BoxApiName;
import org.apache.camel.component.box.internal.BoxConstants;
import org.apache.camel.component.mock.MockEndpoint;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Test class for org.apache.camel.component.box.internal.LongPollingEventsManager APIs.
 */
public class LongPollingEventsManagerIntegrationTest extends AbstractBoxTestSupport {

    private static final Logger LOG = LoggerFactory.getLogger(LongPollingEventsManagerIntegrationTest.class);

    @Test
    public void testPoll() throws Exception {

        // generate file copy event
        final Map<String, Object> headers = new HashMap<String, Object>();
        headers.put("CamelBox.fileId", testFileId);
        final BoxItemCopyRequestObject requestObject = BoxItemCopyRequestObject.copyItemRequestObject("0");
        requestObject.setName(CAMEL_TEST_FILE);
        headers.put("CamelBox.itemCopyRequest", requestObject);

        BoxFile result = requestBodyAndHeaders("direct://COPYFILE", null, headers);

        assertNotNull("copyFile result", result);
        LOG.debug("copyFile: " + result);

        // generate file delete event
        headers.clear();
        headers.put("CamelBox.fileId", result.getId());
        headers.put("CamelBox.defaultRequest", null);
        requestBodyAndHeaders("direct://DELETEFILE", null, headers);

        MockEndpoint mockEndpoint = getMockEndpoint("mock:boxEvents");
        mockEndpoint.expectedMinimumMessageCount(2);
        mockEndpoint.setResultWaitTime(TimeUnit.MILLISECONDS.convert(30, TimeUnit.SECONDS));
        mockEndpoint.assertIsSatisfied();

        final List<Exchange> exchanges = mockEndpoint.getExchanges();
        assertNotNull("poll result", exchanges);
        assertFalse("poll result", exchanges.isEmpty());
        LOG.debug("poll result: " + exchanges);

        for (Exchange exchange : exchanges) {

            assertNotNull("poll result " + BoxConstants.CHUNK_SIZE_PROPERTY,
                    exchange.getIn().getHeader(BoxConstants.CHUNK_SIZE_PROPERTY));
            assertNotNull("poll result " + BoxConstants.NEXT_STREAM_POSITION_PROPERTY,
                    exchange.getIn().getHeader(BoxConstants.NEXT_STREAM_POSITION_PROPERTY));

            final Object body = exchange.getIn().getBody();
            assertNotNull("poll result body", body);
            assertEquals("poll result body type", BoxEvent.class, body.getClass());

            final String eventType = ((BoxEvent) body).getEventType();
            assertTrue("poll result type",
                    BoxEvent.EVENT_TYPE_ITEM_COPY.equals(eventType) || BoxEvent.EVENT_TYPE_ITEM_TRASH.equals(eventType));
        }
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            public void configure() {
                // test route for copyFile
                from("direct://COPYFILE")
                        .to("box://" + BoxApiName.FILES.getName() + "/copyFile");

                // test route for deleteFile
                from("direct://DELETEFILE")
                        .to("box://" + BoxApiName.FILES.getName() + "/deleteFile");

                // test route for poll
                from("box://" + BoxApiName.POLL_EVENTS.getName() + "/poll?streamPosition=-1&streamType=all&limit=100")
                        .to("mock:boxEvents");

            }
        };
    }

    @Override
    protected CamelContext createCamelContext() throws Exception {
        // also test revoke on shutdown
        final CamelContext camelContext = super.createCamelContext();
        final BoxComponent box = (BoxComponent) camelContext.getComponent("box");
        box.getConfiguration().setRevokeOnShutdown(true);
        return camelContext;
    }
}
