/*
 * 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.local.channel.server;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.onosproject.codec.JsonCodec;
import org.onosproject.rest.AbstractWebResource;
import org.opencord.ce.api.models.CarrierEthernetForwardingConstruct;
import org.opencord.ce.api.models.CarrierEthernetNetworkInterface;
import org.opencord.ce.api.models.CarrierEthernetUni;
import org.opencord.ce.api.models.EvcConnId;
import org.opencord.ce.api.services.MetroNetworkVirtualNodeService;
import org.slf4j.Logger;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

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

import static org.slf4j.LoggerFactory.getLogger;

/**
 * Web resource for {@link MetroNetworkVirtualNodeService}
 * APIs.
 */
@Path("carrierethernet")
public class MetroNetworkResource extends AbstractWebResource {
    private final Logger log = getLogger(getClass());
    private static final String FC = "fc";
    private static final String SRC_NI = "srcNi";
    private static final String DST_NI_LIST = "dstNiList";
    private static final String UNI = "uni";

    private JsonCodec<CarrierEthernetForwardingConstruct> fcCodec =
            codec(CarrierEthernetForwardingConstruct.class);
    private JsonCodec<CarrierEthernetNetworkInterface> niCodec =
            codec(CarrierEthernetNetworkInterface.class);

    @Path("ForwardingConstruct")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    @POST
    public Response setNodeForwarding(InputStream stream) {
        try {
            JsonNode responseBody = mapper().readTree(stream);
            log.info(responseBody.toString());
            MetroNetworkVirtualNodeService localNodeService =
                    get(MetroNetworkVirtualNodeService.class);

            CarrierEthernetForwardingConstruct fc =
                    fcCodec.decode((ObjectNode) responseBody.path(FC), this);
            CarrierEthernetNetworkInterface srcNi =
                    niCodec.decode((ObjectNode) responseBody.path(SRC_NI), this);
            Set<CarrierEthernetNetworkInterface> dstNiSet = new HashSet<>();
            responseBody.path(DST_NI_LIST).forEach(jsonDstNi ->
                dstNiSet.add(niCodec.decode((ObjectNode) jsonDstNi, this)));

            localNodeService.setNodeForwarding(fc, srcNi, dstNiSet);
            return Response.status(200).build();
        } catch (IOException io) {
            log.info("Json parse error");
            return Response.status(Response.Status.NOT_ACCEPTABLE).build();
        }
    }

    @Path("createBwp")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    @POST
    public Response createBandwidthProfileResources(InputStream stream) {
        try {
            MetroNetworkVirtualNodeService localNodeService =
                    get(MetroNetworkVirtualNodeService.class);

            JsonNode responseBody = mapper().readTree(stream);
            log.info(responseBody.toString());

            CarrierEthernetForwardingConstruct fc =
                    fcCodec.decode((ObjectNode) responseBody.path(FC), this);
            CarrierEthernetUni uni = (CarrierEthernetUni)
                    niCodec.decode((ObjectNode) responseBody.path(UNI), this);
            localNodeService.createBandwidthProfileResources(fc, uni);
            return Response.status(200).build();
        } catch (IOException io) {
            log.info("Json parse error");
            return Response.status(Response.Status.NOT_ACCEPTABLE).build();
        }
    }

    @Path("applyBwp")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    @POST
    public Response applyBandwidthProfileResources(InputStream stream) {
        try {
            MetroNetworkVirtualNodeService localNodeService =
                    get(MetroNetworkVirtualNodeService.class);

            JsonNode responseBody = mapper().readTree(stream);
            log.info(responseBody.toString());

            CarrierEthernetForwardingConstruct fc =
                fcCodec.decode((ObjectNode) responseBody.path(FC), this);
            CarrierEthernetUni uni = (CarrierEthernetUni)
                niCodec.decode((ObjectNode) responseBody.path(UNI), this);

            localNodeService.applyBandwidthProfileResources(fc, uni);
            return Response.status(200).build();
        } catch (IOException io) {
            log.info("Json parse error");
            return Response.status(Response.Status.NOT_ACCEPTABLE).build();
        }
    }

    @Path("deleteBwp")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    @POST
    public Response removeBandwidthProfileResources(InputStream stream) {
        try {
            MetroNetworkVirtualNodeService localNodeService =
                    get(MetroNetworkVirtualNodeService.class);

            JsonNode responseBody = mapper().readTree(stream);
            log.info(responseBody.toString());

            CarrierEthernetForwardingConstruct fc =
                    fcCodec.decode((ObjectNode) responseBody.path(FC), this);

            CarrierEthernetUni uni = (CarrierEthernetUni)
                    niCodec.decode((ObjectNode) responseBody.path(UNI), this);

            localNodeService.applyBandwidthProfileResources(fc, uni);
            return Response.status(200).build();
        } catch (IOException io) {
            log.info("Json parse error");
            return Response.status(Response.Status.NOT_ACCEPTABLE).build();
        }
    }

    @Path("deleteFcResources/{fcId}")
    @Produces(MediaType.APPLICATION_JSON)
    @GET
    public Response removeAllForwardingResources(@PathParam("{fcId}") String fcId) {
        EvcConnId evcId = EvcConnId.of(fcId);
        MetroNetworkVirtualNodeService localNodeService =
                get(MetroNetworkVirtualNodeService.class);

        localNodeService.removeAllForwardingResources(evcId);
        return Response.status(200).build();
    }
}
