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

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.opencord.ce.api.services.virtualprovider.DefaultDomainVirtualDevice;
import org.opencord.ce.api.services.virtualprovider.DomainVirtualDevice;
import org.opencord.ce.api.services.virtualprovider.EcordDeviceProviderService;
import org.onosproject.codec.JsonCodec;
import org.onosproject.net.DefaultAnnotations;
import org.onosproject.net.DeviceId;
import org.onosproject.net.Port;
import org.onosproject.net.device.DefaultPortDescription;
import org.onosproject.net.device.PortDescription;
import org.onosproject.net.domain.DomainId;
import org.onosproject.rest.AbstractWebResource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.ws.rs.Consumes;
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.ArrayList;
import java.util.List;

/**
 * Remote device REST control.
 */
@Path("/topology/{domainId}")
public class DeviceResource extends AbstractWebResource {
    private final Logger log = LoggerFactory.getLogger(getClass());

    private EcordDeviceProviderService ecordDeviceProviderService =
            get(EcordDeviceProviderService.class);

    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    @Path("{deviceId}")
    public Response postDevice(@PathParam("domainId") String domainId, @PathParam("deviceId") String deviceId,
                               InputStream stream) {
        log.info("Notified device from domainId {}", domainId);
        try {
            JsonNode responseBody = mapper().readTree(stream);
            // the json body superfluous now. Can be used to add annotations to the device later
            log.debug(responseBody.toString());
            DomainVirtualDevice domainDevice = new DefaultDomainVirtualDevice(DeviceId.deviceId(deviceId),
                    DomainId.domainId(domainId));
            ecordDeviceProviderService.connectRemoteDevice(domainDevice);
            return Response.status(200).build();
        } catch (IOException io) {
            log.info("Json parse error");
            return Response.status(Response.Status.NOT_ACCEPTABLE).build();
        }
    }

    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    @Path("{deviceId}/ports")
    public Response postBigSwitchPorts(@PathParam("domainId") String domainId, @PathParam("deviceId") String deviceId,
                                       InputStream stream) {
        log.info("Notified device port from domainId {}", domainId);
        try {
            JsonNode responseBody = mapper().readTree(stream);
            log.debug(responseBody.toString());
            JsonCodec<Port> portCodec = codec(Port.class);
            List<PortDescription> ports = new ArrayList<>();
            responseBody.forEach(item -> {
                Port port = portCodec.decode((ObjectNode) item, this);
                DefaultAnnotations.Builder annot = DefaultAnnotations.builder();
                port.annotations().keys()
                        .forEach(k -> annot.set(k, port.annotations().value(k)));
                ports.add(new DefaultPortDescription(port.number(), port.isEnabled(), port.type(),
                        port.portSpeed(), annot.build()));
            });

            ecordDeviceProviderService.addOrUpdateRemotePorts(DomainId.domainId(domainId),
                    DeviceId.deviceId(deviceId), ports);
            return Response.status(200).build();

        } catch (IOException io) {
            log.info("Json parse error");
            return Response.status(Response.Status.NOT_ACCEPTABLE).build();
        }

    }
}
