/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.eclipse.aether.internal.impl.scope;

import java.util.Collection;
import java.util.Objects;

import org.eclipse.aether.Keys;
import org.eclipse.aether.collection.DependencyCollectionContext;
import org.eclipse.aether.collection.DependencySelector;
import org.eclipse.aether.graph.Dependency;
import org.eclipse.aether.util.artifact.ArtifactIdUtils;

import static java.util.Objects.requireNonNull;

/**
 * A dependency selector that excludes optional dependencies which occur beyond given level.
 * <p>
 * <em>Important note:</em> equals/hashCode must factor in starting state, as instances of this class
 * (potentially differentially configured) are used now in session, but are kept in a set.
 *
 * @see Dependency#isOptional()
 */
public final class OptionalDependencySelector implements DependencySelector {
    public static final Object IGNORED_KEYS = Keys.of(OptionalDependencySelector.class, "ignored");
    public static final Object UNSELECTED_KEYS = Keys.of(OptionalDependencySelector.class, "unselected");

    /**
     * Excludes optional dependencies always (from root).
     */
    public static OptionalDependencySelector fromRoot() {
        return from(1);
    }

    /**
     * Excludes optional transitive dependencies of direct dependencies.
     */
    public static OptionalDependencySelector fromDirect() {
        return from(2);
    }

    /**
     * Excludes optional transitive dependencies from given depth (1=root, 2=direct, 3=transitives of direct ones...).
     */
    public static OptionalDependencySelector from(int applyFrom) {
        if (applyFrom < 1) {
            throw new IllegalArgumentException("applyFrom must be non-zero and positive");
        }
        return new OptionalDependencySelector(Objects.hash(applyFrom), 0, applyFrom, null, null);
    }

    private final int seed;
    private final int depth;
    private final int applyFrom;
    private final Collection<String> ignoredKeys;
    private final Collection<String> unselectedKeys;

    private OptionalDependencySelector(
            int seed, int depth, int applyFrom, Collection<String> ignoredKeys, Collection<String> unselectedKeys) {
        this.seed = seed;
        this.depth = depth;
        this.applyFrom = applyFrom;
        this.ignoredKeys = ignoredKeys; // nullable
        this.unselectedKeys = unselectedKeys; // nullable
    }

    @Override
    public boolean selectDependency(Dependency dependency) {
        requireNonNull(dependency, "dependency cannot be null");
        String key = null;
        if (ignoredKeys != null || unselectedKeys != null) {
            key = ArtifactIdUtils.toId(dependency.getArtifact());
        }
        if (ignoredKeys != null) {
            if (ignoredKeys.contains(key)) {
                return true;
            }
        }
        boolean result = depth < applyFrom || !dependency.isOptional();
        if (!result && unselectedKeys != null) {
            unselectedKeys.add(key);
        }
        return result;
    }

    @Override
    @SuppressWarnings("unchecked")
    public DependencySelector deriveChildSelector(DependencyCollectionContext context) {
        requireNonNull(context, "context cannot be null");
        if (depth >= applyFrom) {
            return this;
        }
        return new OptionalDependencySelector(
                seed,
                depth + 1,
                applyFrom,
                (Collection<String>) context.getSession().getData().get(IGNORED_KEYS),
                (Collection<String>) context.getSession().getData().get(UNSELECTED_KEYS));
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        } else if (null == obj || !getClass().equals(obj.getClass())) {
            return false;
        }

        OptionalDependencySelector that = (OptionalDependencySelector) obj;
        return seed == that.seed && depth == that.depth && applyFrom == that.applyFrom;
    }

    @Override
    public int hashCode() {
        int hash = getClass().hashCode();
        hash = hash * 31 + seed;
        hash = hash * 31 + depth;
        hash = hash * 31 + applyFrom;
        return hash;
    }

    @Override
    public String toString() {
        return String.format("%s(applied: %s)", this.getClass().getSimpleName(), depth >= applyFrom);
    }
}
