/*
 * 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.camel.upgrade.customRecipes;

import org.apache.camel.upgrade.AbstractCamelYamlVisitor;
import org.apache.camel.upgrade.RecipesUtil;
import org.openrewrite.ExecutionContext;
import org.openrewrite.Option;
import org.openrewrite.Preconditions;
import org.openrewrite.Recipe;
import org.openrewrite.TreeVisitor;
import org.openrewrite.yaml.search.FindKey;
import org.openrewrite.yaml.tree.Yaml;

import java.util.Optional;

public class ReplacePropertyInComponentYaml extends Recipe {

    @Option(example = "TODO Provide a usage example for the docs", displayName = "Component",
            description = "Component name.")
    String component;

    @Option(example = "TODO Provide a usage example for the docs", displayName = "Old property key",
            description = "The property key to rename.")
    String oldPropertyKey;

    @Option(example = "TODO Provide a usage example for the docs", displayName = "New prefix before any group",
            description = "The prefix to be replaced with.")
    String newPropertyKey;

    @Option(example = "file:", displayName = "New prefix before value of the changed property",
            description = "This value is appended before the current value of the modified method.",
            required = false)
    String valuePrefix;

    public ReplacePropertyInComponentYaml() {
    }

    public ReplacePropertyInComponentYaml(String component, String oldPropertyKey, String newPropertyKey, String valuePrefix) {
        this.component = component;
        this.oldPropertyKey = oldPropertyKey;
        this.newPropertyKey = newPropertyKey;
        this.valuePrefix = valuePrefix;
    }

    public void setComponent(String component) {
        this.component = component;
    }

    public void setOldPropertyKey(String oldPropertyKey) {
        this.oldPropertyKey = oldPropertyKey;
    }

    public void setNewPropertyKey(String newPropertyKey) {
        this.newPropertyKey = newPropertyKey;
    }

    public void setValuePrefix(String valuePrefix) {
        this.valuePrefix = valuePrefix;
    }

    @Override
    public String getDisplayName() {
        return "Renames property of the component";
    }

    @Override
    public String getDescription() {
        return "ARenames property of the component.";
    }

    @Override
    public TreeVisitor<?, ExecutionContext> getVisitor() {

        return Preconditions.check(RecipesUtil.camelYamlDslPrecondition(), new AbstractCamelYamlVisitor() {

            @Override
            protected void clearLocalCache() {
                //nothing to do
            }

            @Override
            public Yaml.Mapping.Entry doVisitMappingEntry(Yaml.Mapping.Entry entry, ExecutionContext ctx) {
                Yaml.Mapping.Entry e = super.doVisitMappingEntry(entry, ctx);


                String path = RecipesUtil.getProperty(getCursor());
                //yaml fury marshal
                if(path.endsWith("parameters." + oldPropertyKey)) {

                    //find component type
                    Optional<Yaml.Mapping.Entry> compYaml = FindKey.find(getCursor().getParent(3).getValue(), "$.uri").stream()
                            .filter(o -> o instanceof Yaml.Mapping.Entry)
                            .map(o -> (Yaml.Mapping.Entry)o)
                            .findAny();

                    if(compYaml.isPresent()) {
                        String compName = RecipesUtil.getValueFromScalar(compYaml.get().getValue());

                        if (compName != null && (component.equals(compName) || compName.startsWith(component + ":"))) {

                            Yaml.Mapping.Entry newEntry = e.withKey(((Yaml.Scalar) entry.getKey().copyPaste()).withValue(newPropertyKey));

                            if(valuePrefix != null && e.getValue() instanceof Yaml.Scalar && !((Yaml.Scalar)e.getValue()).getValue().startsWith(valuePrefix)) {
                                newEntry = newEntry.withValue(((Yaml.Scalar)e.getValue()).copyPaste().withValue(valuePrefix + ((Yaml.Scalar) newEntry.getValue()).getValue()));
                            }

                            return newEntry;
                        }
                    }
                }

                return e;
            }

        });
    }

}
