package nxm.ucl.test.junit.libg;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import org.junit.Before;

import nxm.sys.lib.Midas;
import nxm.sys.lib.Shell;
import nxm.sys.test.junit.NMTestCase;
import nxm.ucl.libg.MJDatePickerPanel;
import nxm.ucl.libg.MJTimeSpinnerModel;

/** This will test the MJDatePickerPanel class.
 *  Initial testing is for this JDK warning
 *    warning: warning: [serial] non-transient instance field of a serializable class declared with a non-serializable type
 *  @author  Zachary Matthews
 *  @since   NeXtMidas 4.1.2
 */
public final class MJDatePickerPanelTest extends NMTestCase {

  /** public constructor to allow running this test case directly with JUnit. */
  public MJDatePickerPanelTest (String methodName) { this(methodName, null); }

  /** Creates a new instance of the class.
      @param methodName The name of the method being called.
      @param midas      The midas context to use when running the tests.
   */
  public MJDatePickerPanelTest (String methodName, Midas midas) {
    super(methodName, midas);
  }

  private boolean skippingBecauseHeadless = false;

  @Before
  public void setUp () {
    if (Shell.isHeadless()) {
      skippingBecauseHeadless = true;
      return;
    }
  }

  /** Test the case where MJDatePickerPanel serialization will fail */
  public void testUnserializable () {
    if (skippingBecauseHeadless) {
      getMidas().info("Skipping testUnserializable because HEADLESS");
      return;
    }
    MJDatePickerPanel mjDatePickerPanel = new MJDatePickerPanel(null, null, null);
    File ramFile = null;
    try {
      ramFile = File.createTempFile("mjdatepickerpanelserializationtest", "temp");
      FileOutputStream fos = new FileOutputStream(ramFile);
      ObjectOutputStream oos = new ObjectOutputStream(fos);
      oos.writeObject(mjDatePickerPanel);
      oos.flush();
      fos.close();
      FileInputStream fis = new FileInputStream(ramFile);
      ObjectInputStream ois = new ObjectInputStream(fis);
      ois.readObject();
      fis.close();
    }
    catch (UnsupportedOperationException e) {
      String expected = "java.lang.UnsupportedOperationException: " + MJTimeSpinnerModel.UNSERIALIZABLE_MJTIMESPINNERMODEL_OBJECT_MESSAGE;
      assertEquals("MJDatePickerPanel can not serialize unserializable class", expected, e.toString());
    }
    catch (Exception e) {
      fail("Unexpected Exception during serialization:"+e);
    }
    finally {
      ramFile.delete();
    }
  }
}