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

import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.ReferenceCardinality;
import org.onosproject.cluster.ClusterService;
import org.onosproject.cluster.LeadershipService;
import org.onosproject.core.ApplicationId;
import org.onosproject.core.CoreService;
import org.onosproject.net.config.ConfigFactory;
import org.onosproject.net.config.NetworkConfigEvent;
import org.onosproject.net.config.NetworkConfigListener;
import org.onosproject.net.config.NetworkConfigRegistry;
import org.onosproject.net.config.NetworkConfigService;
import org.onosproject.net.config.basics.SubjectFactories;
import org.onosproject.net.device.PortDescription;
import org.opencord.ce.api.models.DomainEndPoint;
import org.opencord.ce.local.bigswitch.BigSwitchEvent;
import org.opencord.ce.local.bigswitch.BigSwitchListener;
import org.opencord.ce.local.bigswitch.BigSwitchService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Component that reacts to the BigSwitch events by notifying the global ONOS orchestrator.
 */
// TODO: better name
@Component(immediate = true)
public class HttpClientComponent {
    private static final String APP_NAME = "org.opencord.ce.local.channel.http";

    // temporary
    private static final String TOPIC_ONE = "ecord-domains-topic-one";

    private final Logger log = LoggerFactory.getLogger(getClass());
    private ApplicationId appId;

    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
    protected ClusterService clusterService;

    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
    protected LeadershipService leadershipService;

    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
    protected NetworkConfigRegistry configRegistry;

    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
    protected NetworkConfigService configService;

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

    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
    protected BigSwitchService bigSwitchService;

    private static DomainEndPoint globalOnos;

    private final ExecutorService eventExecutor =
            Executors.newSingleThreadExecutor();

    private final ConfigFactory<ApplicationId, ConnectionConfig> configFactory =
            new ConfigFactory<ApplicationId, ConnectionConfig>(SubjectFactories.APP_SUBJECT_FACTORY,
                    ConnectionConfig.class, "global") {
                @Override
                public ConnectionConfig createConfig() {
                    return new ConnectionConfig();
                }
            };

    private final NetworkConfigListener configListener = new InternalConfigListener();
    private final BigSwitchListener bigSwitchListener = new InternalBigSwitchListener();

    @Activate
    public void activate() {
        log.info("Started");

        appId = coreService.registerApplication(APP_NAME);
        leadershipService.runForLeadership(TOPIC_ONE);
        configRegistry.registerConfigFactory(configFactory);
        configService.addListener(configListener);
        bigSwitchService.addListener(bigSwitchListener);
        HttpClientInstance.INSTANCE.configure(clusterService, leadershipService);
    }

    @Deactivate
    public void deactivate() {
        log.info("Stopped");
        leadershipService.withdraw(TOPIC_ONE);
        bigSwitchService.removeListener(bigSwitchListener);
        configService.removeListener(configListener);
        configRegistry.unregisterConfigFactory(configFactory);
        if (globalOnos != null) {
            leadershipService.withdraw(globalOnos.topic());
        }
    }

    private void readConfig() {
        globalOnos = configRegistry.getConfig(appId, ConnectionConfig.class)
                        .global();
        if (globalOnos == null) {
            log.error("Configuration failure");
            return;
        }
        leadershipService.runForLeadership(globalOnos.topic());
        HttpClientInstance.INSTANCE.setGlobalOnos(globalOnos);
    }

    private class InternalBigSwitchListener implements BigSwitchListener {

        @Override
        public void event(BigSwitchEvent event) {
            log.info(event.toString());
            switch (event.type()) {
                case DEVICE_CREATED:
                    log.info("DEBUG: DEV_CREATED event");
                    HttpClientInstance.INSTANCE.notifyBigSwitch(bigSwitchService.domainId());
                case PORT_ADDED:
                case PORT_UPDATED:
                case PORT_REMOVED:
                    // the subject is port last updated / added port
                    // but we are not interested in it now
                    List<PortDescription> ports = event.allPorts();
                    HttpClientInstance.INSTANCE.notifyBigSwitchPorts(bigSwitchService.domainId(), ports);
                    break;
                case DEVICE_REMOVED:
                    // TODO
                    break;
                default:
                        break;
            }
        }
    }

    private class InternalConfigListener implements NetworkConfigListener {

        @Override
        public void event(NetworkConfigEvent event) {
            if (!event.configClass().equals(ConnectionConfig.class)) {
                return;
            }
            switch (event.type()) {
                case CONFIG_ADDED:
                    log.info("Network configuration added");
                    eventExecutor.execute(HttpClientComponent.this::readConfig);
                    break;
                case CONFIG_UPDATED:
                    log.info("Network configuration updated");
                    eventExecutor.execute(HttpClientComponent.this::readConfig);
                    break;
                default:
                    break;
            }
        }
    }
}
