// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.execution.testframework.sm.runner.history;

import com.intellij.execution.testframework.sm.runner.GeneralTestEventsProcessor;
import com.intellij.openapi.extensions.ExtensionPointName;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.xml.sax.helpers.DefaultHandler;

import java.io.IOException;
import java.io.Reader;
import java.util.function.Supplier;

/**
 * Extension to import test output from xml file, e.g. generated by <a href="https://github.com/windyroad/JUnit-Schema">ant task</a>
 */
public interface ImportTestOutputExtension {
  ExtensionPointName<ImportTestOutputExtension> EP_NAME = ExtensionPointName.create("com.intellij.importTestOutput");

  /**
   * When extension can parse xml file under reader, then it should return corresponding handler. Otherwise return null.
   *
   * When no custom extension accepts the xml, xml would be parsed as it was exported by IDEA itself {@link ImportTestOutputExtension#findHandler(Supplier, GeneralTestEventsProcessor)}
   *
   * @return handler if xml contains tests output in recognised format,
   *         otherwise null
   */
  @Nullable
  DefaultHandler createHandler(final Reader reader, GeneralTestEventsProcessor processor) throws IOException;

  @NotNull
  static DefaultHandler findHandler(final Supplier<? extends Reader> readerSupplier, GeneralTestEventsProcessor processor) {
    for (ImportTestOutputExtension extension : EP_NAME.getExtensionList()) {
      Reader reader = readerSupplier.get();
      if (reader == null) continue;
      try {
        DefaultHandler handler = extension.createHandler(reader, processor);
        if (handler != null) return handler;
      }
      catch (IOException ignored) {
      }
    }
    return new ImportedTestContentHandler(processor);
  }
}
