/**
 * Copyright (C) 2015 The Gravitee team (http://gravitee.io)
 *
 * 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 io.gravitee.am.gateway.services.sync;

import io.gravitee.am.gateway.core.event.DomainEvent;
import io.gravitee.am.model.Domain;
import io.gravitee.am.repository.management.api.DomainRepository;
import io.gravitee.common.event.EventManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author David BRASSELY (david.brassely at graviteesource.com)
 * @author GraviteeSource Team
 */
public class SyncManager {

    private final Logger logger = LoggerFactory.getLogger(SyncManager.class);

    @Autowired
    private DomainRepository domainRepository;

    @Autowired
    private EventManager eventManager;

    private Map<String, Domain> deployedDomains = new HashMap<>();

    public void refresh() {
        logger.debug("Refreshing sync state...");

        // Registered domains
        Set<Domain> domains = domainRepository.findAll().blockingGet();

        // Look for deleted domains
        if (deployedDomains.size() > domains.size()) {
            Set<String> domainIds = domains.stream().map(domain -> domain.getId()).collect(Collectors.toSet());
            Set<String> deployedDomainIds = new HashSet<>(deployedDomains.keySet());
            deployedDomainIds.forEach(domainId -> {
                if (!domainIds.contains(domainId)) {
                    Domain deployedDomain = deployedDomains.get(domainId);
                    if (deployedDomain != null) {
                        deployedDomains.remove(domainId);
                        eventManager.publishEvent(DomainEvent.UNDEPLOY, deployedDomain);
                    }
                }
            });
        }

        // Look for disabled domains
        domains.stream()
                .filter(domain -> !domain.isEnabled())
                .forEach(domain -> {
                    Domain deployedDomain = deployedDomains.get(domain.getId());
                    if (deployedDomain != null) {
                        deployedDomains.remove(domain.getId());
                        eventManager.publishEvent(DomainEvent.UNDEPLOY, deployedDomain);
                    }
                });

        // Deploy domains
        domains.stream()
                .filter(domain -> domain.isEnabled() && !domain.isMaster())
                .forEach(domain -> {
                    Domain deployedDomain = deployedDomains.get(domain.getId());
                    if (deployedDomain == null) {
                        eventManager.publishEvent(DomainEvent.DEPLOY, domain);
                        deployedDomains.put(domain.getId(), domain);
                    } else {
                        // Check last update date
                        if (domain.getUpdatedAt().after(deployedDomain.getUpdatedAt())) {
                            eventManager.publishEvent(DomainEvent.UPDATE, domain);
                            deployedDomains.put(domain.getId(), domain);
                        }
                    }
                });
    }
}

@@ -1015,85 +1015,9 @@
 til.
-HashMap;%0Aimport java.util.HashSet;%0Aimport java.util.Map;%0Aimport java.util.Set
+*
 ;%0Aim
@@ -1613,16 +1613,494 @@
 indAll()
+%0A                // remove master domains%0A                .map(registeredDomains -%3E %7B%0A                    if (registeredDomains != null) %7B%0A                        return registeredDomains%0A                                .stream()%0A                                .filter(domain -%3E !domain.isMaster())%0A                                .collect(Collectors.toSet());%0A                    %7D%0A                    return Collections.%3CDomain%3EemptySet();%0A                %7D)%0A                
 .blockin
@@ -3428,30 +3428,8 @@
 ed()
- && !domain.isMaster()
 )%0A  

fix previous 'do not load master domain' commit