// Copyright (c) 2013 VMware, Inc. All Rights Reserved.
// Copyright (C) 2017 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.vmware.gerrit.owners.common;

import com.google.gerrit.extensions.api.GerritApi;
import com.google.gerrit.extensions.api.changes.AddReviewerInput;
import com.google.gerrit.extensions.api.changes.ChangeApi;
import com.google.gerrit.extensions.api.changes.ReviewInput;
import com.google.gerrit.extensions.common.ChangeInfo;
import com.google.gerrit.extensions.restapi.RestApiException;
import com.google.gerrit.reviewdb.client.Account;
import com.google.gerrit.reviewdb.client.Account.Id;
import com.google.gerrit.server.IdentifiedUser;
import com.google.gerrit.server.change.ChangesCollection;
import com.google.gerrit.server.project.ChangeControl;
import com.google.gerrit.server.util.ManualRequestContext;
import com.google.gerrit.server.util.OneOffRequestContext;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import java.util.ArrayList;
import java.util.Collection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Singleton
public class ReviewerManager {
  private static final Logger log = LoggerFactory.getLogger(ReviewerManager.class);

  private final OneOffRequestContext requestContext;
  private final GerritApi gApi;
  private final IdentifiedUser.GenericFactory userFactory;
  private final ChangesCollection changes;

  @Inject
  public ReviewerManager(
      OneOffRequestContext requestContext,
      GerritApi gApi,
      IdentifiedUser.GenericFactory userFactory,
      ChangesCollection changes) {
    this.requestContext = requestContext;
    this.gApi = gApi;
    this.userFactory = userFactory;
    this.changes = changes;
  }

  public void addReviewers(ChangeApi cApi, Collection<Account.Id> reviewers)
      throws ReviewerManagerException {
    try {
      ChangeInfo changeInfo = cApi.get();
      try (ManualRequestContext ctx =
          requestContext.openAs(new Account.Id(changeInfo.owner._accountId))) {
        ChangeControl changeControl = changes.parse(change.getId()).getControl();
        // TODO(davido): Switch back to using changes API again,
        // when it supports batch mode for adding reviewers
        ReviewInput in = new ReviewInput();
        in.reviewers = new ArrayList<>(reviewers.size());
        for (Account.Id account : reviewers) {
          if (isVisibleTo(changeControl, account)) {
            AddReviewerInput addReviewerInput = new AddReviewerInput();
            addReviewerInput.reviewer = account.toString();
            in.reviewers.add(addReviewerInput);
          } else {
            log.warn(
                "Not adding account {} as reviewer to change {} because the associated ref is not visible",
                account,
                change.getId());
          }
          gApi.changes().id(changeInfo.id).current().review(in);
        }
      }
    } catch (RestApiException | OrmException e) {
      log.error("Couldn't add reviewers to the change", e);
      throw new ReviewerManagerException(e);
    }
  }

  private boolean isVisibleTo(ChangeControl changeControl, Id account) {
    return changeControl.forUser(userFactory.create(account)).isRefVisible();
  }
}

@@ -1160,16 +1160,166 @@
 unt.Id;%0A
+import com.google.gerrit.reviewdb.client.Change;%0Aimport com.google.gerrit.reviewdb.client.Project;%0Aimport com.google.gerrit.reviewdb.server.ReviewDb;%0A
 import c
@@ -1394,29 +1394,33 @@
 ver.
-change.ChangesCollect
+permissions.ChangePermiss
 ion;
@@ -1457,28 +1457,93 @@
 er.p
-roject.ChangeControl
+ermissions.PermissionBackend;%0Aimport com.google.gerrit.server.query.change.ChangeData
 ;%0Aim
@@ -2181,35 +2181,99 @@
 l Change
-sCollection changes
+Data.Factory changeDataFactory;%0A  private final PermissionBackend permissionBackend
 ;%0A%0A  @In
@@ -2433,27 +2433,81 @@
 ange
-sCollection changes
+Data.Factory changeDataFactory,%0A      PermissionBackend permissionBackend
 ) %7B%0A
@@ -2625,19 +2625,87 @@
 ange
-s = changes
+DataFactory = changeDataFactory;%0A    this.permissionBackend = permissionBackend
 ;%0A  
@@ -2998,90 +2998,8 @@
 ) %7B%0A
-        ChangeControl changeControl = changes.parse(change.getId()).getControl();%0A
     
@@ -3295,28 +3295,58 @@
 ibleTo(c
-hangeControl
+tx.getReviewDbProvider().get(), changeInfo
 , accoun
@@ -3731,16 +3731,20 @@
 ange
-.getId()
+Info._number
 );%0A 
@@ -4037,126 +4037,367 @@
 eTo(
-ChangeControl changeControl, Id account) %7B%0A    return changeControl.forUser(userFactory.create(account)).isRefVisible(
+ReviewDb reviewDb, ChangeInfo changeInfo, Id account) %7B%0A    ChangeData changeData =%0A        changeDataFactory.create(%0A            reviewDb, new Project.NameKey(changeInfo.project), new Change.Id(changeInfo._number));%0A    return permissionBackend%0A        .user(userFactory.create(account))%0A        .change(changeData)%0A        .testOrFalse(ChangePermission.READ
 );%0A 

Implement visibility using permission backend