package org.apache.torque.generator.merge;

/*
 * 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.
 */

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;

import org.apache.torque.generator.GeneratorException;
import org.eclipse.jgit.diff.RawText;
import org.eclipse.jgit.diff.RawTextComparator;
import org.eclipse.jgit.merge.MergeAlgorithm;
import org.eclipse.jgit.merge.MergeFormatter;
import org.eclipse.jgit.merge.MergeResult;

/**
 * Can execute a three-way merge. This class is thread safe.
 *
 * @version $Id: ThreeWayMerger.java 1917241 2024-04-21 13:29:41Z tv $
 */
public class ThreeWayMerger
{
    /**
     * Performs a three-way merge.
     *
     * @param base the base from which the other two versions are derived,
     *        not null.
     * @param generated the newly generated text, not null.
     * @param edited the possibly edited text, not null.
     * @param charsetName the name of the character set, not null.
     * @return the merge result, not null.
     *
     * @throws GeneratorException if merging fails.
     */
    public String merge(
            String base,
            String generated,
            String edited,
            Charset charSet)
                    throws GeneratorException
    {
        MergeAlgorithm mergeAlgorithm = new MergeAlgorithm();
        MergeResult<RawText> mergeResult = mergeAlgorithm.merge(
                RawTextComparator.DEFAULT,
                new RawText(base.getBytes(charSet)),
                new RawText(generated.getBytes(charSet)),
                new RawText(edited.getBytes(charSet)));

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try
        {
            new MergeFormatter().formatMerge(
                    outputStream,
                    mergeResult,
                    "base",
                    "generated",
                    "edited",
                    charSet);
        }
        catch (IOException e)
        {
            throw new GeneratorException("could nor render merge result", e);
        }

        return new String(outputStream.toByteArray(), charSet);
    }
}
