/*
 * 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.apache.tinkerpop.gremlin.process.traversal.strategy.verification;

import org.apache.tinkerpop.gremlin.process.computer.traversal.step.VertexComputing;
import org.apache.tinkerpop.gremlin.process.computer.traversal.strategy.finalization.ComputerFinalizationStrategy;
import org.apache.tinkerpop.gremlin.process.traversal.Step;
import org.apache.tinkerpop.gremlin.process.traversal.Traversal;
import org.apache.tinkerpop.gremlin.process.traversal.TraversalStrategy;
import org.apache.tinkerpop.gremlin.process.traversal.step.ReadOnlyTraversalParent;
import org.apache.tinkerpop.gremlin.process.traversal.step.branch.RepeatStep;
import org.apache.tinkerpop.gremlin.process.traversal.step.filter.DiscardStep;
import org.apache.tinkerpop.gremlin.process.traversal.step.filter.DropStep;
import org.apache.tinkerpop.gremlin.process.traversal.step.filter.FilterStep;
import org.apache.tinkerpop.gremlin.process.traversal.step.map.LabelStep;
import org.apache.tinkerpop.gremlin.process.traversal.step.map.LabelsStep;
import org.apache.tinkerpop.gremlin.process.traversal.step.sideEffect.InjectStep;
import org.apache.tinkerpop.gremlin.process.traversal.step.sideEffect.ProfileSideEffectStep;
import org.apache.tinkerpop.gremlin.process.traversal.step.sideEffect.SideEffectCapStep;
import org.apache.tinkerpop.gremlin.process.traversal.step.util.ReducingBarrierStep;
import org.apache.tinkerpop.gremlin.process.traversal.step.util.RequirementsStep;
import org.apache.tinkerpop.gremlin.process.traversal.step.util.SupplyingBarrierStep;
import org.apache.tinkerpop.gremlin.process.traversal.step.util.WithOptions;
import org.apache.tinkerpop.gremlin.process.traversal.strategy.AbstractTraversalStrategy;
import org.apache.tinkerpop.gremlin.process.traversal.strategy.decoration.OptionsStrategy;
import org.apache.tinkerpop.gremlin.process.traversal.util.ReadOnlyChildValidator;
import org.apache.tinkerpop.gremlin.process.traversal.util.TraversalHelper;
import org.apache.tinkerpop.gremlin.structure.Graph;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

/**
 * @author Marko A. Rodriguez (http://markorodriguez.com)
 * @author Stephen Mallette (http://stephen.genoprime.com)
 */
public final class StandardVerificationStrategy extends AbstractTraversalStrategy<TraversalStrategy.VerificationStrategy> implements TraversalStrategy.VerificationStrategy {

    private static final StandardVerificationStrategy INSTANCE = new StandardVerificationStrategy();

    private StandardVerificationStrategy() {
    }

    @Override
    public void apply(final Traversal.Admin<?, ?> traversal) {
        if (!traversal.getStrategies().getStrategy(ComputerFinalizationStrategy.class).isPresent() &&
                !traversal.getStrategies().getStrategy(ComputerVerificationStrategy.class).isPresent()) {
            if (!TraversalHelper.getStepsOfAssignableClass(VertexComputing.class, traversal).isEmpty())
                throw new VerificationException("VertexComputing steps must be executed with a GraphComputer: " + TraversalHelper.getStepsOfAssignableClass(VertexComputing.class, traversal), traversal);
        }

        for (final Step<?, ?> step : traversal.getSteps()) {
            for (String label : new HashSet<>(step.getLabels())) {
                if (Graph.Hidden.isHidden(label))
                    step.removeLabel(label);
            }
            
            if (step instanceof InjectStep && TraversalHelper.hasRepeatStepParent(step.getTraversal()))
                throw new VerificationException("The parent of inject()-step can not be repeat()-step: " + step, traversal);

            if ((step instanceof ReducingBarrierStep || step instanceof SupplyingBarrierStep) &&
                    step.getTraversal().getParent() instanceof RepeatStep &&
                    step.getTraversal().getParent().getGlobalChildren().get(0).getSteps().contains(step))
                throw new VerificationException("The parent of a reducing/supplying barrier can not be repeat()-step: " + step, traversal);

            // prevents silly stuff like g.V().emit()
            if (step instanceof RepeatStep && null == ((RepeatStep) step).getRepeatTraversal())
                throw new VerificationException("The repeat()-traversal was not defined:" + traversal, traversal);

            if (step instanceof ReadOnlyTraversalParent) {
                for (final Traversal.Admin<?, ?> child : ((ReadOnlyTraversalParent) step).getLocalChildren()) {
                    try {
                        ReadOnlyChildValidator.validate(child);
                    } catch (final IllegalArgumentException e) {
                        throw new VerificationException(e.getMessage(), traversal);
                    }
                }
                for (final Traversal.Admin<?, ?> child : ((ReadOnlyTraversalParent) step).getGlobalChildren()) {
                    try {
                        ReadOnlyChildValidator.validate(child);
                    } catch (final IllegalArgumentException e) {
                        throw new VerificationException(e.getMessage(), traversal);
                    }
                }
            }

        }

        // Reject a traversal source configured with both with("multilabel") and with("singlelabel") — the
        // options are mutually exclusive and combining them has no sensible interpretation.
        final boolean hasConflictingLabelOptions = traversal.getStrategies().getStrategy(OptionsStrategy.class)
                .map(os -> os.getOptions().containsKey(WithOptions.MULTILABEL_KEY)
                        && os.getOptions().containsKey(WithOptions.SINGLELABEL_KEY))
                .orElse(false);
        if (hasConflictingLabelOptions) {
            throw new VerificationException(
                    "with(\"multilabel\") and with(\"singlelabel\") are mutually exclusive and cannot both be configured on the same traversal source.",
                    traversal);
        }

        // Reject label().drop() and labels().drop() patterns — users should use dropLabel(label) or dropLabels() instead
        for (final DropStep<?> dropStep : TraversalHelper.getStepsOfAssignableClass(DropStep.class, traversal)) {
            Step<?, ?> current = dropStep.getPreviousStep();

            // Walk backward through filter steps (IsStep, HasStep, WhereStep, NotStep, etc.)
            while (current instanceof FilterStep) {
                current = current.getPreviousStep();
            }

            if (current instanceof LabelsStep || current instanceof LabelStep) {
                throw new VerificationException(
                        "label().drop() and labels().drop() are not supported. Use dropLabel(label) or dropLabels() instead.",
                        traversal);
            }
        }

        // The ProfileSideEffectStep must be one of the following
        // (1) the last step
        // (2) 2nd last step when accompanied by the cap step or none step (i.e. iterate() to nothing)
        // (3) 3rd to last when the traversal ends with a RequirementsStep.
        final Step<?, ?> endStep = traversal.asAdmin().getEndStep();
        if (TraversalHelper.hasStepOfClass(ProfileSideEffectStep.class, traversal) &&
                !(endStep instanceof ProfileSideEffectStep ||
                        (endStep instanceof SideEffectCapStep && endStep.getPreviousStep() instanceof ProfileSideEffectStep) ||
                        (endStep instanceof DiscardStep && endStep.getPreviousStep() instanceof SideEffectCapStep && endStep.getPreviousStep().getPreviousStep() instanceof ProfileSideEffectStep) ||
                        (endStep instanceof RequirementsStep && endStep.getPreviousStep() instanceof SideEffectCapStep && endStep.getPreviousStep().getPreviousStep() instanceof ProfileSideEffectStep) ||
                        (endStep instanceof RequirementsStep && endStep.getPreviousStep() instanceof DiscardStep && endStep.getPreviousStep().getPreviousStep() instanceof SideEffectCapStep && endStep.getPreviousStep().getPreviousStep().getPreviousStep() instanceof ProfileSideEffectStep))) {
            throw new VerificationException("When specified, the profile()-Step must be the last step or followed only by the cap()-step.", traversal);
        }

        if (TraversalHelper.getStepsOfClass(ProfileSideEffectStep.class, traversal).size() > 1) {
            throw new VerificationException("The profile()-Step cannot be specified multiple times.", traversal);
        }
    }

    public static StandardVerificationStrategy instance() {
        return INSTANCE;
    }

    @Override
    public Set<Class<? extends VerificationStrategy>> applyPrior() {
        return Collections.singleton(ComputerVerificationStrategy.class);
    }
}
