package nxm.sys.test.junit.lib;

import java.lang.reflect.Method;

import nxm.sys.lib.HttpResource;
import nxm.sys.lib.IOResource;
import nxm.sys.lib.Midas;
import nxm.sys.lib.Shell;
import nxm.sys.lib.Table;
import nxm.sys.lib.TarResource;
import nxm.sys.test.junit.NMTestCase;

/**
 * This will test the IOResource class.
 * @author Kevin Esterheld
 * @since NeXtMidas 3.8.0
 */
public class IOResourceTest extends NMTestCase {
  private Midas M;

  /**
   * public constructor to allow running this test case directly with JUnit.
   * @param methodName The name of the method being called.
   */
  public IOResourceTest (String methodName) {
    this(methodName,  new Midas());
  }

  /**
   * This constructor is required by NeXtMidas Unit Testing framework.
   * @param methodName  The name of the method being called.
   * @param midas       The midas context to use when running the tests.
   */
  public IOResourceTest (String methodName, Midas midas) {
    super(methodName, midas);
  }
  @Override
  public void setUp () {
    //The Midas contet is needed when running tests. This will get the global midas context.
    M = getMidas();
  }

  /**
   * Test case to confirm that when it is an HTTPS url that it will be assigned the http resource.
   * Also confirms that if it is not http resource that it will not be assigned the http resource.
   */
  public void testGetUserResource() {
    Midas M = Shell.getMidasContext();
    if (Shell.isGradleBuild()) {
      M.warning("nxm.sys.junit.lib.IOResourceTest skipping testGetUserResource() because fails in Gradle build");
      return;
    }
    Class<IOResource> ioResource = IOResource.class;

    try {
      Method method = ioResource.getDeclaredMethod("getUserResourceHandler",String.class);
      method.setAccessible(true);
      String testHttps = "https://somesite.com/somepage";
      String testHttp = "http://somesite.com";
      String tarFile = "tar://somesite.com";

      assertTrue("getUserResource() will fail if the https resource is not defined.",method.invoke(null, testHttps ) instanceof HttpResource);
      assertTrue("getUserResource() will fail if the tar resource is not defined.",method.invoke(null, tarFile ) instanceof TarResource);
      assertNull("getUserResource() should return null for undefined resource",method.invoke(null, testHttp ));
    }
    catch (Exception e) {
      fail("Failed test with exception:"+e);
    }
  }

  /** Test the the Resource Group case is getting fully initialized */
  public void testGetInstance () {
    Table t = new Table("{RG=HTTPS}");
    IOResource ior = IOResource.getInstance(M, IOResource.HTTP, "http://nextmidas.com/nmdownloads/test/hugefile.tmp", IOResource.DIR_OUTPUT, t);
    assertEquals("getInstance() with quals with RG (Resource Group) gets fully initialized.", M,ior.getContext());
  }
}