// Copyright (C) 2018 The Android Open Source Project
//
// Licensed 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 com.google.gerrit.server;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.gerrit.entities.PatchLineComment.Status.PUBLISHED;
import static java.util.stream.Collectors.toSet;

import com.google.common.collect.ImmutableList;
import com.google.gerrit.common.Nullable;
import com.google.gerrit.entities.Comment;
import com.google.gerrit.entities.PatchSet;
import com.google.gerrit.exceptions.StorageException;
import com.google.gerrit.extensions.validators.CommentForValidation;
import com.google.gerrit.extensions.validators.CommentValidationFailure;
import com.google.gerrit.extensions.validators.CommentValidator;
import com.google.gerrit.server.notedb.ChangeNotes;
import com.google.gerrit.server.patch.PatchListCache;
import com.google.gerrit.server.patch.PatchListNotAvailableException;
import com.google.gerrit.server.plugincontext.PluginSetContext;
import com.google.gerrit.server.update.ChangeContext;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import java.util.Collection;
import java.util.Map;

@Singleton
public class PublishCommentUtil {
  private final PatchListCache patchListCache;
  private final PatchSetUtil psUtil;
  private final CommentsUtil commentsUtil;

  @Inject
  PublishCommentUtil(
      CommentsUtil commentsUtil, PatchListCache patchListCache, PatchSetUtil psUtil) {
    this.commentsUtil = commentsUtil;
    this.psUtil = psUtil;
    this.patchListCache = patchListCache;
  }

  public void publish(
      ChangeContext ctx, PatchSet.Id psId, Collection<Comment> drafts, @Nullable String tag) {
    ChangeNotes notes = ctx.getNotes();
    checkArgument(notes != null);
    if (drafts.isEmpty()) {
      return;
    }

    Map<PatchSet.Id, PatchSet> patchSets =
        psUtil.getAsMap(notes, drafts.stream().map(d -> psId(notes, d)).collect(toSet()));
    for (Comment d : drafts) {
      PatchSet ps = patchSets.get(psId(notes, d));
      if (ps == null) {
        throw new StorageException("patch set " + ps + " not found");
      }
      d.writtenOn = ctx.getWhen();
      d.tag = tag;
      // Draft may have been created by a different real user; copy the current real user. (Only
      // applies to X-Gerrit-RunAs, since modifying drafts via on_behalf_of is not allowed.)
      ctx.getUser().updateRealAccountId(d::setRealAuthor);
      try {
        CommentsUtil.setCommentCommitId(d, patchListCache, notes.getChange(), ps);
      } catch (PatchListNotAvailableException e) {
        throw new StorageException(e);
      }
    }
    commentsUtil.putComments(ctx.getUpdate(psId), PUBLISHED, drafts);
  }

  private static PatchSet.Id psId(ChangeNotes notes, Comment c) {
    return PatchSet.id(notes.getChangeId(), c.key.patchSetId);
  }

  /**
   * Helper to run the specified set of {@link CommentValidator}-s on the specified comments.
   *
   * @return See {@link CommentValidator#validateComments(ImmutableList)}.
   */
  public static ImmutableList<CommentValidationFailure> findInvalidComments(
      PluginSetContext<CommentValidator> commentValidators,
      ImmutableList<CommentForValidation> commentsForValidation) {
    ImmutableList.Builder<CommentValidationFailure> commentValidationFailures =
        new ImmutableList.Builder<>();
    commentValidators.runEach(
        listener ->
            commentValidationFailures.addAll(listener.validateComments(commentsForValidation)));
    return commentValidationFailures.build();
  }
}

@@ -2132,16 +2132,22 @@
 ext ctx,
+%0A     
  PatchSe
@@ -2156,16 +2156,22 @@
 Id psId,
+%0A     
  Collect
@@ -2188,18 +2188,31 @@
 t%3E draft
-s,
+Comments,%0A     
  @Nullab
@@ -2315,16 +2315,23 @@
 f (draft
+Comment
 s.isEmpt
@@ -2437,16 +2437,23 @@
 s, draft
+Comment
 s.stream
@@ -2521,16 +2521,27 @@
 nt d
+raftComment
  : draft
 s) %7B
@@ -2540,13 +2540,86 @@
 raft
+Comment
 s) %7B%0A
+      PatchSet.Id psIdOfDraftComment = psId(notes, draftComment);%0A
     
@@ -2652,26 +2652,30 @@
 get(psId
-(notes, d)
+OfDraftComment
 );%0A     
@@ -2745,16 +2745,32 @@
 t %22 + ps
+IdOfDraftComment
  + %22 not
@@ -2794,16 +2794,27 @@
 %0A      d
+raftComment
 .written
@@ -2840,16 +2840,27 @@
 %0A      d
+raftComment
 .tag = t
@@ -3094,16 +3094,27 @@
 ountId(d
+raftComment
 ::setRea
@@ -3176,16 +3176,27 @@
 mmitId(d
+raftComment
 , patchL
@@ -3399,16 +3399,23 @@
 D, draft
+Comment
 s);%0A  %7D%0A

Fix exception message if patch set not found