/*
 * Copyright (C) 2016 Google Inc.
 *
 * 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.copybara.git;

import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.copybara.GeneralOptions;
import com.google.copybara.Option;
import com.google.copybara.RepoException;
import com.google.copybara.authoring.Author;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.function.Supplier;
import java.util.logging.Logger;
import javax.annotation.Nullable;

/**
 * Arguments for {@link GitDestination}, {@link GitOrigin}, and other Git components.
 */
@Parameters(separators = "=")
public final class GitDestinationOptions implements Option {
  private final Logger logger = Logger.getLogger(GitDestinationOptions.class.getName());

  private final Supplier<GeneralOptions> generalOptions;
  private final GitOptions gitOptions;

  @VisibleForTesting
  @Parameter(names = "--git-committer-name",
      description = "If set, overrides the committer name for the generated commits in git"
          + " destination.")
  public String committerName = "";

  @VisibleForTesting
  @Parameter(names = "--git-committer-email",
      description = "If set, overrides the committer e-mail for the generated commits in git"
          + " destination.")
  public String committerEmail = "";

  public GitDestinationOptions(Supplier<GeneralOptions> generalOptions,
      GitOptions gitOptions) {
    this.generalOptions = Preconditions.checkNotNull(generalOptions);
    this.gitOptions = Preconditions.checkNotNull(gitOptions);
  }

  Author getCommitter() {
    return new Author(committerName, committerEmail);
  }

  @Parameter(names = "--git-destination-url",
      description = "If set, overrides the git destination URL.")
  String url = null;

  @Nullable
  @Parameter(names = "--git-destination-fetch",
      description = "If set, overrides the git destination fetch reference.")
  public String fetch = null;

  @Nullable
  @Parameter(names = "--git-destination-push",
      description = "If set, overrides the git destination push reference.")
  public String push = null;

  @Nullable
  @Parameter(names = "--git-destination-path",
      description = "If set, the tool will use this directory for the local repository."
          + " Note that if the directory exists it needs to be a git repository. Copybara will"
          + " revert any staged/unstaged changes.")
  String localRepoPath = null;

  @Parameter(names = "--git-destination-skip-push",
      description = "If set, the tool will not push to the remote destination")
  boolean skipPush = false;

  @Parameter(names = "--git-destination-last-rev-first-parent",
      description = "Use git --first-parent flag when looking for last-rev in previous commits")
  boolean lastRevFirstParent = false;

  @Parameter(names = "--git-destination-non-fast-forward",
      description = "Allow non-fast-forward pushes to the destination. We only allow this when"
          + " used with different push != fetch references.")
  boolean nonFastForwardPush = false;


  /**
   * Returns a non-bare repo. Either because it uses a custom worktree or because it is a user
   * non-bare repo.
   *
   * <p> The git database (git-dir) might be potentially shared between multiple workflows. This
   * means that the users should force fetch and probably create its own local unique references.
   */
  GitRepository localGitRepo(String url) throws RepoException {
    try {
      if (Strings.isNullOrEmpty(localRepoPath)) {
        return gitOptions.cachedBareRepoForUrl(url)
            .withWorkTree(generalOptions.get().getDirFactory().newTempDir("git_dest"));
      }
      Path path = Paths.get(localRepoPath);

      if (!Files.exists(path)
          || Files.isDirectory(path) && isGitRepoOrEmptyDir(path)) {
        Files.createDirectories(path);
        return GitRepository.initScratchRepo(
            generalOptions.get().isVerbose(), path, generalOptions.get().getEnvironment());

      }
      throw new RepoException(path + " is not empty and is not a git repository");
    } catch (IOException e) {
      throw new RepoException("Cannot create local repository", e);
    }
  }

  private static boolean isGitRepoOrEmptyDir(Path path) throws IOException {
    return Files.exists(path.resolve(".git")) || !Files.list(path).findAny().isPresent();
  }

}

@@ -1158,41 +1158,8 @@
 er;%0A
-import java.util.logging.Logger;%0A
 impo
@@ -1377,97 +1377,8 @@
 on %7B
-%0A  private final Logger logger = Logger.getLogger(GitDestinationOptions.class.getName());
 %0A%0A  
@@ -4341,22 +4341,13 @@
 ath)
-%0A         
  %7C%7C 
+(
 File
@@ -4391,24 +4391,25 @@
 tyDir(path))
+)
  %7B%0A        F

Fix a couple of warnings