/*
 * ====================================================================
 * 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.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 *
 */
package org.apache.hc.core5.jackson2.http.examples;

import java.net.URI;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import org.apache.hc.core5.concurrent.FutureCallback;
import org.apache.hc.core5.http.HttpResponse;
import org.apache.hc.core5.http.Message;
import org.apache.hc.core5.http.impl.bootstrap.AsyncRequesterBootstrap;
import org.apache.hc.core5.http.impl.bootstrap.HttpAsyncRequester;
import org.apache.hc.core5.http.protocol.HttpCoreContext;
import org.apache.hc.core5.io.CloseMode;
import org.apache.hc.core5.jackson2.http.AsyncJsonClientPipeline;
import org.apache.hc.core5.reactor.IOReactorConfig;
import org.apache.hc.core5.util.Timeout;

/**
 * This example demonstrates how an HTTP response JSON content can be consumed as
 * Jackson JsonNode object.
 * <p>
 * Please note content of incoming and outgoing HTTP messages gets streamed without making
 * a copy of the message body content in an intermediate buffer.
 * <p>
 * This example uses {@link AsyncJsonClientPipeline} to simplify HTTP message execution pipeline
 * assembly. One can also use JSON message request producers and response consumers directly.
 */
public class JsonNodeResponseExample {

    public static void main(final String... args) throws Exception {
        final IOReactorConfig ioReactorConfig = IOReactorConfig.custom()
                .setSoTimeout(5, TimeUnit.SECONDS)
                .build();

        // Create and start requester
        final HttpAsyncRequester requester = AsyncRequesterBootstrap.bootstrap()
                .setIOReactorConfig(ioReactorConfig)
                .create();

        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            System.out.println("HTTP requester shutting down");
            requester.close(CloseMode.GRACEFUL);
        }));
        requester.start();

        final URI uri = URI.create("http://httpbin.org/get");

        System.out.println("Executing GET " + uri);

        final ObjectMapper objectMapper = new ObjectMapper();
        final CountDownLatch latch = new CountDownLatch(1);
        requester.execute(
                AsyncJsonClientPipeline.assemble(objectMapper)
                        .request()
                        .get(uri)
                        .response()
                        .asJsonNode()
                        .result(new FutureCallback<Message<HttpResponse, JsonNode>>() {

                            @Override
                            public void completed(final Message<HttpResponse, JsonNode> m) {
                                System.out.println("Response status: " + m.head().getCode());
                                System.out.println(m.body());
                                latch.countDown();
                            }

                            @Override
                            public void failed(final Exception ex) {
                                ex.printStackTrace(System.out);
                                latch.countDown();
                            }

                            @Override
                            public void cancelled() {
                                latch.countDown();
                            }

                        })
                        .create(),
                Timeout.ofMinutes(1),
                HttpCoreContext.create());

        latch.await();

        System.out.println("Shutting down I/O reactor");
        requester.initiateShutdown();
    }

}
