// Copyright 2000-2020 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 org.jetbrains.idea.maven.project;

import com.intellij.testFramework.UsefulTestCase;
import com.intellij.ui.TextFieldWithHistory;
import com.intellij.util.Consumer;
import com.intellij.util.ReflectionUtil;
import org.jetbrains.idea.maven.server.MavenServerManager;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

import java.lang.reflect.Field;
import java.util.Collections;

@RunWith(JUnit4.class)
public class MavenEnvironmentFormTest extends UsefulTestCase {

  @Test
  public void shouldNotShowDuplicatedBundledMavenHome() {
    MavenGeneralPanel panel = new MavenGeneralPanel();
    assertThat(panel,
               t -> assertSameElements("Absolute path to bundled maven should not present", t.getHistory(),
                                       Collections.singleton(MavenServerManager.BUNDLED_MAVEN_3)));
  }

  @Test
  public void shouldSetBundledMavenIfSetAbsolutePath() {
    MavenGeneralSettings settings = new MavenGeneralSettings();
    MavenGeneralPanel panel = new MavenGeneralPanel();
    settings.setMavenHome(MavenServerManager.BUNDLED_MAVEN_3);
    panel.getData(settings);
    assertThat(panel,
               t -> assertEquals("Absolute path to bundled maven should resolve to bundle", MavenServerManager.BUNDLED_MAVEN_3,
                                 t.getText()));
  }

  @Test
  public void shouldNotSetBundledMavenIfAnotherMavenSet() {
    MavenGeneralSettings settings = new MavenGeneralSettings();
    MavenGeneralPanel panel = new MavenGeneralPanel();
    settings.setMavenHome("/path/to/maven/home");
    panel.getData(settings);
    assertThat(panel,
               t -> assertEquals("/path/to/maven/home", t.getText()));
  }

  private void assertThat(MavenGeneralPanel configurable, Consumer<TextFieldWithHistory> checker) {
    MavenEnvironmentForm form = getValue(MavenEnvironmentForm.class, configurable, "mavenPathsForm");
    TextFieldWithHistory mavenHomeField = getValue(TextFieldWithHistory.class, form, "mavenHomeField");
    checker.consume(mavenHomeField);
  }

  protected <T> T getValue(Class<T> fieldClass, Object object, String name) {
    try {
      Field field = ReflectionUtil.findAssignableField(object.getClass(), fieldClass, name);
      return ReflectionUtil.getFieldValue(field, object);
    }
    catch (NoSuchFieldException e) {
      fail("No such field " + name + " in " + object);
      return null;
    }
  }
}
@@ -820,74 +820,25 @@
 sert
-SameElements(%22Absolute path to bundled maven should not present%22, 
+ContainsElements(
 t.ge
@@ -945,24 +945,227 @@
 MAVEN_3)));%0A
+    assertThat(panel,%0A               t -%3E assertDoesntContain(t.getHistory(),%0A                                           MavenServerManager.resolveEmbeddedMavenHome().getMavenHome().getAbsolutePath()));%0A
   %7D%0A%0A  @Test

fix test