/*
 * Copyright 2017-present Open Networking Laboratory
 *
 * 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.opencord.ce.global.virtualdomain;

import com.fasterxml.jackson.databind.SerializationFeature;
import org.glassfish.jersey.client.ClientProperties;
import org.onosproject.rest.AbstractWebResource;
import org.slf4j.Logger;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import static java.net.HttpURLConnection.HTTP_OK;
import static org.slf4j.LoggerFactory.getLogger;
import static org.opencord.ce.global.virtualdomain.config.XosEndPointConfig.XosEndPoint;

/**
 * Implementation of REST client for XOS Metro-net service.
 */
public class XoSHttpClient extends AbstractWebResource {
    protected final Logger log = getLogger(getClass());

    private static final int DEFAULT_TIMEOUT_MS = 2000;

    private XosEndPoint xosEndPoint;
    private final Client client = ClientBuilder.newClient();


    public XoSHttpClient(XosEndPoint xosEndPoint) {
        this.xosEndPoint = xosEndPoint;

        client.property(ClientProperties.CONNECT_TIMEOUT, DEFAULT_TIMEOUT_MS);
        client.property(ClientProperties.READ_TIMEOUT, DEFAULT_TIMEOUT_MS);
        mapper().enable(SerializationFeature.INDENT_OUTPUT);
    }

    public void restPut(String body, String cpeId) {
        WebTarget webTarget = client.target("http://" + xosEndPoint.ipAddress().toString() +
                 xosEndPoint.resource() + "/" + cpeId);
        Response response;
        response = webTarget.request(MediaType.APPLICATION_JSON)
                .put(Entity.entity(body, MediaType.APPLICATION_JSON));
        try {
            if (response.getStatus() != HTTP_OK) {
                log.warn("Failed to put resource {}", xosEndPoint.resource());
            }
        } catch (javax.ws.rs.ProcessingException e) {
            log.error("Javax process exception in XoSClientHttp: {}", e.getMessage());
        }
    }
}
