package nxm.sys.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.libg.MJTextArea;
import nxm.sys.test.junit.NMTestCase;

/** This will test the MJTextArea 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.1
 */
public final class MJTextAreaTest extends NMTestCase {

  /** public constructor to allow running this test case directly with JUnit. */
  public MJTextAreaTest (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 MJTextAreaTest (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 MJTextArea serialization will fail */
  public void testUnserializable () {
    if (skippingBecauseHeadless) {
      getMidas().info("Skipping testUnserializable because HEADLESS");
      return;
    }
    MJTextArea mjTextArea = new MJTextArea("test");
    File ramFile = null;
    try {
      ramFile = File.createTempFile("mjpanelserializationtest", "temp");
      FileOutputStream fos = new FileOutputStream(ramFile);
      ObjectOutputStream oos = new ObjectOutputStream(fos);
      oos.writeObject(mjTextArea);
      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: " + MJTextArea.UNSERIALIZABLE_MJTEXTAREA_OBJECT_MESSAGE;
      assertEquals("MJTextArea can not serialize unserializable class", expected, e.toString());
    }
    catch (Exception e) {
      fail("Unexpected Exception during serialization:"+e);
    }
    finally {
      ramFile.delete();
    }
  }
}
