/*
 * Copyright 2000-2009 JetBrains s.r.o.
 *
 * 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.intellij.openapi.vcs.changes.actions;

import com.intellij.icons.AllIcons;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.vcs.VcsBundle;
import com.intellij.openapi.vcs.VcsDataKeys;
import com.intellij.openapi.vcs.VcsException;
import com.intellij.openapi.vcs.changes.*;
import com.intellij.openapi.vcs.changes.patch.CreatePatchCommitExecutor;
import com.intellij.openapi.vcs.changes.shelf.ShelvedChangeList;
import com.intellij.openapi.vcs.changes.shelf.ShelvedChangesViewManager;
import com.intellij.openapi.vcs.changes.ui.SessionDialog;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author yole
 */
public class CreatePatchFromChangesAction extends AnAction implements DumbAware {
  public CreatePatchFromChangesAction() {
    super(VcsBundle.message("action.name.create.patch.for.selected.revisions"),
          VcsBundle.message("action.description.create.patch.for.selected.revisions"), AllIcons.Actions.CreatePatch);
  }

  public void actionPerformed(AnActionEvent e) {
    Project project = e.getData(PlatformDataKeys.PROJECT);
    final Change[] changes = e.getData(VcsDataKeys.CHANGES);
    if ((changes == null) || (changes.length == 0)) return;
    String commitMessage = null;
    ShelvedChangeList[] shelvedChangeLists = e.getData(ShelvedChangesViewManager.SHELVED_CHANGELIST_KEY);
    if (shelvedChangeLists != null && shelvedChangeLists.length > 0) {
      commitMessage = shelvedChangeLists [0].DESCRIPTION;
    }
    else {
      ChangeList[] changeLists = e.getData(VcsDataKeys.CHANGE_LISTS);
      if (changeLists != null && changeLists.length > 0) {
        commitMessage = changeLists [0].getComment();
      }
    }
    if (commitMessage == null) {
      commitMessage = e.getData(VcsDataKeys.PRESET_COMMIT_MESSAGE);
    }
    if (commitMessage == null) {
      commitMessage = "";
    }
    List<Change> changeCollection = new ArrayList<Change>();
    Collections.addAll(changeCollection, changes);
    createPatch(project, commitMessage, changeCollection);
  }

  public static void createPatch(Project project, String commitMessage, List<Change> changeCollection) {
    project = project == null ? ProjectManager.getInstance().getDefaultProject() : project;
    final CreatePatchCommitExecutor executor = CreatePatchCommitExecutor.getInstance(project);
    CommitSession commitSession = executor.createCommitSession();
    if (commitSession instanceof CommitSessionContextAware) {
      ((CommitSessionContextAware)commitSession).setContext(new CommitContext());
    }
    DialogWrapper sessionDialog = new SessionDialog(executor.getActionText(),
                                                    project,
                                                    commitSession,
                                                    changeCollection,
                                                    commitMessage);
    sessionDialog.show();
    if (!sessionDialog.isOK()) {
      return;
    }
    preloadContent(project, changeCollection);

    commitSession.execute(changeCollection, commitMessage);
  }

  private static void preloadContent(final Project project, final List<Change> changes) {
    // to avoid multiple progress dialogs, preload content under one progress
    ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() {
      public void run() {
        for(Change change: changes) {
          checkLoadContent(change.getBeforeRevision());
          checkLoadContent(change.getAfterRevision());
        }
      }

      private void checkLoadContent(final ContentRevision revision) {
        ProgressManager.checkCanceled();
        if (revision != null && !(revision instanceof BinaryContentRevision)) {
          try {
            revision.getContent();
          }
          catch (VcsException e1) {
            // ignore at the moment
          }
        }
      }
    }, VcsBundle.message("create.patch.loading.content.progress"), true, project);
  }

  public void update(final AnActionEvent e) {
    final Boolean haveSelectedChanges = e.getData(VcsDataKeys.HAVE_SELECTED_CHANGES);
    ChangeList[] changeLists = e.getData(VcsDataKeys.CHANGE_LISTS);
    final String presetMessage = e.getData(VcsDataKeys.PRESET_COMMIT_MESSAGE);
    e.getPresentation().setEnabled(Boolean.TRUE.equals(haveSelectedChanges) &&
                                   ((changeLists == null || changeLists.length == 1)) || (presetMessage != null));
  }
}

@@ -5102,36 +5102,32 @@
 GES);%0A    Change
-List
 %5B%5D changeLists =
@@ -5123,322 +5123,337 @@
 ange
-Lists = e.getData(VcsDataKeys.CHANGE_LISTS);%0A    final String presetMessage = e.getData(VcsDataKeys.PRESET_COMMIT_MESSAGE);%0A    e.getPresentation().setEnabled(Boolean.TRUE.equals(haveSelectedChanges) &&%0A                                   ((changeLists == null %7C%7C changeLists.length == 1)) %7C%7C (presetMessage != null
+s;%0A    ChangeList%5B%5D lists;%0A    e.getPresentation().setEnabled(Boolean.TRUE.equals(haveSelectedChanges) &&%0A                                   ((lists = e.getData(VcsDataKeys.CHANGE_LISTS)) != null && lists.length == 1) &&%0A                                   ((changes = e.getData(VcsDataKeys.CHANGES)) != null && changes.length %3E 0
 ));%0A

create patch from committed changes now works only for 1 list at a time: IDEA-88458 "Create patch..." command on repository revisions treeview doesn't working