#!/usr/bin/python

from numpy.testing import *
from pyepl.transarchive import Archive
from pyepl.hardware import pollEvents
from pyepl.exputils import Experiment
from pyepl.eeg import EEGTrack
from pyepl import timing
import os
from shutil import rmtree

basename = "eeg"
archive_name = "eeg_test_output"
test_duration = 10000

required_events = ['EXPSTART_TRAIN', 'TRAIN_UP', 'TRAIN_DN', 'UP', 'DN']

class test_eeg(NumpyTestCase):
    def setUp(self):
        self.exp = Experiment(use_eeg=False)
        print "Created Experiment object."
        self.eeg = EEGTrack(basename, Archive(archive_name), autoStart=False)
        print "Created EEGTrack object."

    def check_callback(self):
        """
        Loop for several seconds as sync pulses get sent
        intermittently.  If we last for more than a few seconds there
        are no problems with the pollEvents recursion_level.
        """
        try:
            mstime = timing.now()
            self.eeg.startService()
            self.eeg.startLogging()
            while True:
                if timing.now()-mstime >= test_duration:
                    break
                pollEvents()
        except:
            print "Caught exception."
        
        # inspect output file
        assert self.inspectLog(), "Didn't find a required EEG pulse event." 

    def inspectLog(self):
        """
        Check the log file for the events listed under required_events.
        """
        logname = os.path.join(archive_name, basename + "." + basename + "log")
        logfile = open(logname)
        lines = logfile.readlines()
        
        for e in required_events:
            found = False
            for l in lines:
                cols = l.split()
                if cols[-1]==e:
                    found = True
                    break
            if not found: # if we got here without finding a required
                          # event-class, something's wrong
                return False

        return True

    def tearDown(self):
        self.eeg.stopLogging()
        self.eeg.stopService()
        del self.exp
        del self.eeg
        rmtree(archive_name)

if __name__ == '__main__':
    NumpyTest().run()

