package com.atlassian.stash.internal.scm.git.pull;

import com.atlassian.bitbucket.content.ChangeCallback;
import com.atlassian.bitbucket.content.ChangeType;
import com.atlassian.bitbucket.pull.PullRequest;
import com.atlassian.bitbucket.scm.git.command.merge.conflict.GitMergeConflict;
import com.atlassian.bitbucket.scm.pull.PullRequestChangeCommandParameters;
import com.google.common.base.Charsets;
import com.google.common.io.Files;

import java.io.*;

/**
 * Produces a file containing detailed information about the {@link GitMergeConflict conflicts} encountered while
 * merging a pull request. The resulting file can then be stored using {@code git notes add} to save the conflict
 * details so they can be displayed in the {@code git diff-tree} output.
 *
 * @since 1.3
 * @see com.atlassian.stash.internal.scm.git.DefaultGitPullRequestCommandFactory#changes(PullRequest, PullRequestChangeCommandParameters, ChangeCallback)
 * @see com.atlassian.stash.internal.scm.git.command.notes.ConflictMapNotesOutputHandler
 */
public class MergeConflictNoteWriter implements Closeable {

    private final BufferedWriter writer;

    public MergeConflictNoteWriter(File notesFile) throws IOException {
        writer = Files.newWriter(notesFile, Charsets.UTF_8);
    }

    @Override
    public void close() throws IOException {
        writer.close();
    }

    public void writeBranches(String fromBranch, String toBranch) throws IOException {
        writer.write("From: " + fromBranch);
        writer.write('\n');
        writer.write("To: " + toBranch);
        writer.write('\n');
    }

    public void writeChange(ChangeType type, String path, String srcPath) throws IOException {
        writer.write('\t');
        writer.write(type.name());
        writer.write('|');
        writer.write(path);
        if (srcPath != null) {
            writer.write("|");
            writer.write(srcPath);
        }
        writer.write('\n');
    }

    public void writeConflict(GitMergeConflict conflict) throws IOException {
        writer.write("Conflict: (");
        writer.write(conflict.getType().getReason());
        writer.write(") ");
        writer.write(conflict.getMessage());
        writer.write('\n');
    }
}
