/*
 * Copyright 2017-present Open Networking Foundation
 *
 * 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.client;

import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.ReferenceCardinality;
import org.onlab.packet.ChassisId;
import org.onosproject.core.CoreService;
import org.onosproject.net.ConnectPoint;
import org.onosproject.net.DefaultAnnotations;
import org.onosproject.net.Device;
import org.onosproject.net.DeviceId;
import org.onosproject.net.Link;
import org.onosproject.net.MastershipRole;
import org.onosproject.net.Port;
import org.onosproject.net.PortNumber;
import org.onosproject.net.SparseAnnotations;
import org.onosproject.net.device.DefaultDeviceDescription;
import org.onosproject.net.device.DefaultPortDescription;
import org.onosproject.net.device.DeviceDescription;
import org.onosproject.net.device.DeviceProvider;
import org.onosproject.net.device.DeviceProviderRegistry;
import org.onosproject.net.device.DeviceProviderService;
import org.onosproject.net.device.PortDescription;
import org.onosproject.net.link.DefaultLinkDescription;
import org.onosproject.net.link.LinkDescription;
import org.onosproject.net.link.LinkProvider;
import org.onosproject.net.link.LinkProviderRegistry;
import org.onosproject.net.link.LinkProviderService;
import org.onosproject.net.provider.ProviderId;
import org.slf4j.Logger;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;

import static org.slf4j.LoggerFactory.getLogger;

/**
 * Inject fake topology elements.
 */
//@Component(immediate = true)
public class TestTopology implements DeviceProvider,
        LinkProvider {
    public static final String PROVIDER_NAME = "org.opencord.ce.local.test";
    public static final ProviderId PROVIDER_ID = new ProviderId("test", PROVIDER_NAME);
    private static final String UNKNOWN = "unknown";

    private final Logger log = getLogger(getClass());
    public static final String TEST_DEV_PREFIX = "test:0000";
    public static final int NUM = 1;

    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
    protected CoreService coreService;

    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
    protected DeviceProviderRegistry deviceProviderRegistry;

    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
    protected LinkProviderRegistry linkProviderRegistry;

    protected DeviceProviderService deviceProviderService;
    protected LinkProviderService linkProviderService;

    @Override
    public ProviderId id() {
        return PROVIDER_ID;
    }

    @Activate
    public void activate() {
        coreService.registerApplication(PROVIDER_NAME);
        deviceProviderService = deviceProviderRegistry.register(this);
        linkProviderService = linkProviderRegistry.register(this);

        new Thread(this::buildFakeNetwork).start();

        log.info("Started");
    }

    @Deactivate
    public void deactivate() {
        deviceProviderRegistry.unregister(this);
        linkProviderRegistry.unregister(this);
        log.info("Stopped");
    }

    @Override
    public void triggerProbe(DeviceId deviceId){

    }

    @Override
    public void roleChanged(DeviceId deviceId, MastershipRole newRole) {

    }

    @Override
    public boolean isReachable(DeviceId deviceId) {
        return true;
    }

    @Override
    public void changePortState(DeviceId deviceId, PortNumber portNumber,
                                boolean enable) {

    }

    private void buildFakeNetwork() {
        ChassisId chassisId = new ChassisId();
        SparseAnnotations annotations = DefaultAnnotations.builder()
                .set("no-lldp", "any")
                .set("test", "test")
                .build();
        int i;
        int j;
        for (i = 1; i <= NUM; i++) {
            DeviceId deviceId = DeviceId.deviceId(TEST_DEV_PREFIX + i);
            DeviceDescription deviceDescription = new DefaultDeviceDescription(
                    deviceId.uri(),
                    Device.Type.SWITCH,
                    UNKNOWN, UNKNOWN, UNKNOWN, UNKNOWN,
                    chassisId, annotations);
            deviceProviderService.deviceConnected(deviceId, deviceDescription);
            List<PortDescription> ports = new ArrayList<>();
            for (j = 1; j <= NUM; j++) {
                ports.add(new DefaultPortDescription(PortNumber.portNumber(j),
                        true, Port.Type.FIBER, 10000,
                        annotations));

            }
            deviceProviderService.updatePorts(deviceId, ports);

            String macString = randomMCAddress();
            log.info("MacString: {}", macString);
/*
            HostDescription hostDescription = new DefaultHostDescription(MacAddress.valueOf(macString),
                    VlanId.NONE,
                    new HostLocation(deviceId, PortNumber.portNumber(1), 0),
                    annotations);
            hostProviderService.hostDetected(hostId, hostDescription, true);
            */
        }

        long seed = (long) ThreadLocalRandom.current().nextDouble();
        Random rand = new Random(seed);
        for (i = 1; i <= NUM; i++) {
            for (j = i + 1; j <= NUM; j++) {


                if (rand.nextDouble() > 0.5) {
                    continue;
                }

                LinkDescription linkDescription = new DefaultLinkDescription(
                        ConnectPoint.deviceConnectPoint(TEST_DEV_PREFIX + i + "/" + j),
                        ConnectPoint.deviceConnectPoint(TEST_DEV_PREFIX + j + "/" + (i + 1)),
                        Link.Type.DIRECT,
                        true,
                        annotations
                );
                LinkDescription linkDescription1 = new DefaultLinkDescription(
                        ConnectPoint.deviceConnectPoint(TEST_DEV_PREFIX + j + "/" + (i + 1)),
                        ConnectPoint.deviceConnectPoint(TEST_DEV_PREFIX + i + "/" + j),
                        Link.Type.DIRECT,
                        true,
                        annotations
                );
                linkProviderService.linkDetected(linkDescription);
                linkProviderService.linkDetected(linkDescription1);
            }
        }
    }
    private String randomMCAddress() {
        Random rand = new Random();
        byte[] macAddr = new byte[6];
        rand.nextBytes(macAddr);

        macAddr[0] = (byte) (macAddr[0] & (byte) 254);  //zeroing last 2
        // bytes to make it unicast and locally adminstrated
        StringBuilder sb = new StringBuilder(18);
        for (byte b : macAddr) {

            if (sb.length() > 0) {
                sb.append(":");
            }
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }



}
