// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.provision.maintenance;

import com.yahoo.config.provision.ApplicationId;
import com.yahoo.config.provision.Deployer;
import com.yahoo.log.LogLevel;
import com.yahoo.vespa.hosted.provision.Node;
import com.yahoo.vespa.hosted.provision.NodeRepository;

import java.time.Duration;
import java.time.Instant;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;

/**
 * The application maintainer regularly redeploys all applications to make sure the node repo and application
 * model is in sync and to trigger background node allocation changes such as allocation optimizations and
 * flavor retirement.
 *
 * @author bratseth
 */
public class PeriodicApplicationMaintainer extends ApplicationMaintainer {
    private final Duration minTimeBetweenRedeployments;
    private final Instant start;

    public PeriodicApplicationMaintainer(Deployer deployer, NodeRepository nodeRepository, 
                                         Duration interval, Duration minTimeBetweenRedeployments, JobControl jobControl) {
        super(deployer, nodeRepository, interval, jobControl);
        this.minTimeBetweenRedeployments = minTimeBetweenRedeployments;
        this.start = Instant.now();
    }

    @Override
    protected boolean canDeployNow(ApplicationId application) {
        // Don't deploy if a regular deploy just happened
        return getLastDeployTime(application).isBefore(nodeRepository().clock().instant().minus(minTimeBetweenRedeployments));
    }

    // Returns the app that was deployed the longest time ago
    @Override
    protected Set<ApplicationId> applicationsNeedingMaintenance() {
        if (waitInitially()) return new HashSet<>();

        Optional<ApplicationId> app = (nodesNeedingMaintenance().stream()
                .map(node -> node.allocation().get().owner())
                .filter(this::shouldBeDeployedOnThisServer)
                .min(Comparator.comparing(this::getLastDeployTime)));
        app.ifPresent(applicationId -> log.log(LogLevel.INFO, applicationId + " will be deployed, last deploy time " +
                getLastDeployTime(applicationId)));
        return app.map(applicationId -> new HashSet<>(Collections.singletonList(applicationId))).orElseGet(HashSet::new);
    }

    private Instant getLastDeployTime(ApplicationId application) {
        return deployer().lastDeployTime(application).orElse(Instant.EPOCH);
    }

    // We only know last deploy time for applications that were deployed on this config server,
    // the rest will be deployed on another config server
    protected boolean shouldBeDeployedOnThisServer(ApplicationId application) {
        return deployer().lastDeployTime(application).isPresent();
    }

    // TODO: Do not start deploying until some time has gone (ideally only until bootstrap of config server is finished)
    protected boolean waitInitially() {
        return Instant.now().isBefore(start.plus(minTimeBetweenRedeployments));
    }

    @Override
    protected List<Node> nodesNeedingMaintenance() {
        return nodeRepository().getNodes(Node.State.active);
    }

}

@@ -510,34 +510,8 @@
 or;%0A
-import java.util.HashSet;%0A
 impo
@@ -1857,29 +1857,36 @@
  return 
-new Hash
+Collections.empty
 Set
-%3C%3E
 ();%0A%0A   
@@ -2346,39 +2346,8 @@
 map(
-applicationId -%3E new HashSet%3C%3E(
 Coll
@@ -2353,17 +2353,18 @@
 lections
-.
+::
 singleto
@@ -2368,52 +2368,41 @@
 eton
-List(applicationId))).orElseGet(HashSet::new
+).orElseGet(Collections::emptySet
 );%0A 

Use immutable collections instead