package com.intellij.diagnostic;

import com.intellij.CommonBundle;
import com.intellij.errorreport.ErrorReportSender;
import com.intellij.errorreport.bean.ErrorBean;
import com.intellij.errorreport.bean.NotifierBean;
import com.intellij.errorreport.error.InternalEAPException;
import com.intellij.errorreport.error.NewBuildException;
import com.intellij.errorreport.error.NoSuchEAPUserException;
import com.intellij.ide.DataManager;
import com.intellij.idea.IdeaLogger;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.diagnostic.ErrorReportSubmitter;
import com.intellij.openapi.diagnostic.IdeaLoggingEvent;
import com.intellij.openapi.diagnostic.SubmittedReportInfo;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.util.net.IOExceptionDialog;
import org.jetbrains.annotations.NonNls;

import javax.swing.*;
import java.awt.*;
import java.io.IOException;

/**
 * Created by IntelliJ IDEA.
 * User: max
 * Date: Feb 17, 2005
 * Time: 11:12:23 PM
 * To change this template use File | Settings | File Templates.
 */
public class ITNReporter extends ErrorReportSubmitter {
  private static int previousExceptionThreadId = 0;
  private static boolean wasException = false;
  @NonNls private static final String URL_HEADER = "http://www.intellij.net/tracker/idea/viewSCR?publicId=";

  public String getReportActionText() {
    return DiagnosticBundle.message("error.report.to.jetbrains.action");
  }

  public SubmittedReportInfo submit(IdeaLoggingEvent[] events, Component parentComponent) {
    return sendError(events[0], parentComponent);
  }

  /**
     * @noinspection ThrowablePrintStackTrace
     */
  private static SubmittedReportInfo sendError(IdeaLoggingEvent event, Component parentComponent) {
    NotifierBean notifierBean = new NotifierBean();
    ErrorBean errorBean = new ErrorBean();
    errorBean.autoInit();
    errorBean.setLastAction(IdeaLogger.ourLastActionId);

    int threadId = 0;
    SubmittedReportInfo.SubmissionStatus submissionStatus = SubmittedReportInfo.SubmissionStatus.FAILED;

    final DataContext dataContext = DataManager.getInstance().getDataContext(parentComponent);
    Project project = PlatformDataKeys.PROJECT.getData(dataContext);

    String description = "";
    do {
      // prepare
      try {
        ErrorReportSender sender = ErrorReportSender.getInstance();

        sender.prepareError(project, event.getThrowable());

        EAPSendErrorDialog dlg = new EAPSendErrorDialog();
        dlg.setErrorDescription(description);
        dlg.show();

        @NonNls String itnLogin = ErrorReportConfigurable.getInstance().ITN_LOGIN;
        @NonNls String itnPassword = ErrorReportConfigurable.getInstance().getPlainItnPassword();
        if (itnLogin.trim().length() == 0 && itnPassword.trim().length() == 0) {
          itnLogin = "idea_anonymous";
          itnPassword = "guest";
        }
        notifierBean.setItnLogin(itnLogin);
        notifierBean.setItnPassword(itnPassword);

        description = dlg.getErrorDescription();
        String message = event.getMessage();

        @NonNls StringBuilder descBuilder = new StringBuilder();
        if (description.length() > 0) {
          descBuilder.append("User description: ").append(description).append("\n");
        }
        if (message != null) {
          descBuilder.append("Error message: ").append(message).append("\n");
        }
        if (previousExceptionThreadId != 0) {
          descBuilder.append("Previous exception is: ").append(URL_HEADER).append(previousExceptionThreadId).append("\n");
        }
        if (wasException) {
          descBuilder.append("There was at least one exception before this one.\n");
        }

        errorBean.setDescription(descBuilder.toString());

        if (dlg.isShouldSend()) {
          threadId = sender.sendError(notifierBean, errorBean);
          previousExceptionThreadId = threadId;
          wasException = true;
          submissionStatus = SubmittedReportInfo.SubmissionStatus.NEW_ISSUE;

          Messages.showInfoMessage(parentComponent,
                                   DiagnosticBundle.message("error.report.confirmation"),
                                   ReportMessages.ERROR_REPORT);
          break;
        }
        else {
          break;
        }

      }
      catch (NoSuchEAPUserException e) {
        if (Messages.showYesNoDialog(parentComponent, DiagnosticBundle.message("error.report.authentication.failed"),
                                     ReportMessages.ERROR_REPORT, Messages.getErrorIcon()) != 0) {
          break;
        }
      }
      catch (InternalEAPException e) {
        if (Messages.showYesNoDialog(parentComponent, DiagnosticBundle.message("error.report.posting.failed", e.getMessage()),
                                     ReportMessages.ERROR_REPORT, Messages.getErrorIcon()) != 0) {
          break;
        }
      }
      catch (IOException e) {
        if (!IOExceptionDialog.showErrorDialog(DiagnosticBundle.message("error.report.exception.title"),
                                               DiagnosticBundle.message("error.report.failure.message"))) {
          break;
        }
      }
      catch (NewBuildException e) {
        Messages.showMessageDialog(parentComponent,
                                   DiagnosticBundle.message("error.report.new.eap.build.message", e.getMessage()), CommonBundle.getWarningTitle(),
                                   Messages.getWarningIcon());
        break;
      }
      catch (Exception e) {
        if (Messages.showYesNoDialog(JOptionPane.getRootFrame(), DiagnosticBundle.message("error.report.sending.failure"),
                                     ReportMessages.ERROR_REPORT, Messages.getErrorIcon()) != 0) {
          break;
        }
      }

    }
    while (true);

    return new SubmittedReportInfo(submissionStatus != SubmittedReportInfo.SubmissionStatus.FAILED ? URL_HEADER + threadId : null,
                                   String.valueOf(threadId),
                                   submissionStatus);
  }
}

@@ -423,24 +423,78 @@
 ataManager;%0A
+import com.intellij.ide.plugins.IdeaPluginDescriptor;%0A
 import com.i
@@ -514,24 +514,24 @@
 IdeaLogger;%0A
-
 import com.i
@@ -631,16 +631,76 @@
 taKeys;%0A
+import com.intellij.openapi.application.ApplicationManager;%0A
 import c
@@ -869,16 +869,65 @@
 rtInfo;%0A
+import com.intellij.openapi.extensions.PluginId;%0A
 import c
@@ -1175,154 +1175,19 @@
 %0A * 
-Created by IntelliJ IDEA.%0A * User: max%0A * Date: Feb 17, 2005%0A * Time: 11:12:23 PM%0A * To change this template use File %7C Settings %7C File Templates.
+@author max
 %0A */
@@ -3517,32 +3517,555 @@
 %5Cn%22);%0A        %7D%0A
+%0A        Throwable t = event.getThrowable();%0A        if (t != null) %7B%0A          final PluginId pluginId = IdeErrorsDialog.findPluginId(t);%0A          if (pluginId != null) %7B%0A            final IdeaPluginDescriptor ideaPluginDescriptor = ApplicationManager.getApplication().getPlugin(pluginId);%0A            if (ideaPluginDescriptor != null && !ideaPluginDescriptor.isBundled()) %7B%0A              descBuilder.append(%22Plugin version: %22).append(ideaPluginDescriptor.getVersion()).append(%22%5Cn%22);%0A            %7D%0A          %7D%0A        %7D%0A%0A
         if (prev

include version of non-bundled plugin in exception report