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


import com.google.common.collect.Sets;

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.domain.DomainService;
import org.opencord.ce.api.services.channel.ControlChannelListenerService;
import org.opencord.ce.api.models.DomainEndPoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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


/**
 * Southbound component that adds a listener to the
 * {@link ControlChannelListenerService}.
 *
 * Accomplishes network tasks through HTTP requests,
 * acting as a client that send {@link org.opencord.ce.api.models.CarrierEthernetForwardingConstruct}
 * requests to the underlying domains
 */
@Component(immediate = true)
public class HttpClientComponent {
    private static final String APP_NAME = "org.opencord.ce.global.channel.http";

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

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

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

    @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 ControlChannelListenerService channelListenerService;

    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
    protected DomainService domainService;

    private static boolean isRunningForLeadership = false;

    private final Set<DomainEndPoint> endPoints = Sets.newHashSet();
    private final List<String> topics = new ArrayList<>();

    private final ExecutorService eventExecutor =
            Executors.newSingleThreadExecutor();

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

    private final NetworkConfigListener configListener = new InternalConfigListener();

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

        appId = coreService.registerApplication(APP_NAME);
        configRegistry.registerConfigFactory(configFactory);
        configService.addListener(configListener);
        channelListenerService.addListener(HttpClientInstance.INSTANCE);
    }

    @Deactivate
    protected void deactivate() {
        log.info("Stopped");
        configService.removeListener(configListener);
        configRegistry.unregisterConfigFactory(configFactory);
        channelListenerService.removeListener(HttpClientInstance.INSTANCE);
        if (isRunningForLeadership) {
            topics.forEach(topic -> leadershipService.withdraw(topic));
        }
    }

    private void runForLeadership(List<String> topics) {
        topics.forEach(topic ->
            leadershipService.runForLeadership(topic));
        isRunningForLeadership = true;
    }


    private void readConfig() {
        ConnectionConfig config = configRegistry.getConfig(appId, ConnectionConfig.class);
        log.debug("Domains connections config received");

        endPoints.addAll(config.endPoints());
        topics.addAll(config.topics());
        runForLeadership(topics);
        HttpClientInstance.INSTANCE.configure(clusterService, leadershipService, domainService, endPoints);
    }

    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;
            }
        }
    }
}
