#!/usr/bin/env python

import sys, os
import unittest

import gi
gi.require_version('v_sim', '3.8')
from gi.repository import GLib, v_sim

import signals

class TestToolFiles(unittest.TestCase):
  def ascii_text(self, path = None, string = None):
    f = v_sim.Files.new()
    if path is not None:
      try:
        f.open(path)
      except GLib.Error as e:
        if e.code != GLib.FileError.FAILED:
          raise
        return
    if string is not None:
      f.fromMemory(string)
    (s, l, pos) = f.read_line_string()
    self.assertEqual(s, GLib.IOStatus.NORMAL)
    self.assertEqual(l.str, "Some ASCII data.\n")
    (s, l, pos) = f.read_line_string()
    self.assertEqual(s, GLib.IOStatus.NORMAL)
    self.assertEqual(l.str, "\n")
    (s, l, pos) = f.read_line_string()
    self.assertEqual(s, GLib.IOStatus.EOF)
    self.assertEqual(l.str, '')
    s = f.rewind()
    self.assertEqual(s, GLib.IOStatus.NORMAL)
    (s, l, pos) = f.read_line_string()
    self.assertEqual(s, GLib.IOStatus.NORMAL)
    self.assertEqual(l.str, "Some ASCII data.\n")

  def test_ascii_text(self):
    self.ascii_text(None, """Some ASCII data.

""")
    self.ascii_text(os.path.join(os.path.dirname(sys.argv[0]), "ascii_text"))
    self.ascii_text(os.path.join(os.path.dirname(sys.argv[0]), "ascii_text.bz2"))

  def fortran_data(self, path):
    f = v_sim.Files.new()
    try:
      f.fortran_open(path)
    except GLib.Error as e:
      if e.code != GLib.FileError.FAILED:
        raise
      return
    (ok, endian) = f.fortran_testEndianness(128)
    self.assertTrue(ok)
    self.assertEqual(endian, v_sim.FortranEndianId.KEEP)
    (ok, lbl) = f.fortran_readString(128, endian, False)
    self.assertTrue(ok)
    self.assertEqual(lbl, "Some title text.")
    ok = f.fortran_checkFlag(128, endian)
    self.assertTrue(ok)
    (ok, n) = f.fortran_readFlag(endian)
    self.assertTrue(ok)
    self.assertEqual(n, 12)
    (ok, nat) = f.fortran_readInteger(endian)
    self.assertTrue(ok)
    self.assertEqual(nat, 3)
    (ok, dbl) = f.fortran_readDouble(endian)
    self.assertTrue(ok)
    self.assertEqual(dbl, 1.)
    ok = f.fortran_checkFlag(n, endian)
    self.assertTrue(ok)
    (ok, rxyz) = f.fortran_readDoubleArray(9, endian, True)
    self.assertTrue(ok)
    self.assertEqual(rxyz[0:3], [1., 2., 3.])
    self.assertEqual(rxyz[3:6], [7., 8., 9.])

  def test_fortran_data(self):
    self.fortran_data(os.path.join(os.path.dirname(sys.argv[0]), "fortran_data"))
    self.fortran_data(os.path.join(os.path.dirname(sys.argv[0]), "fortran_data.bz2"))

if __name__ == '__main__':
    unittest.main()
