import unittest
import os, glob
from SMART.Java.Python.mapperAnalyzer import MapperAnalyzer
from commons.core.parsing.GffParser import GffParser

class Test_F_mapperAnalyzer(unittest.TestCase):

    def setUp(self):
        self.readsFileName   = "inputFile.fastq"
        self.mappingFileName = "inputFile.sam"
        self.outputFileName  = "outputFile.gff3"
         
    def tearDown(self):
        for fileRoot in (self.readsFileName, self.mappingFileName, self.outputFileName):
            for file in glob.glob("%s*" % (fileRoot)):
                os.remove(file)
        os.system("rm tmpNames_* tmpSequences_* smartdb*")

    def test_run_simple(self):
        handle = open(self.readsFileName, "w")
        handle.write("@read1\n")
        handle.write("AAAAAAAAAAAAAAAAAAAA\n")
        handle.write("+\n")
        handle.write("AAAAAAAAAAAAAAAAAAAA\n")
        handle.write("@read2\n")
        handle.write("CCCCCCCCCCCCCCCCCCCC\n")
        handle.write("+\n")
        handle.write("AAAAAAAAAAAAAAAAAAAA\n")
        handle.close()
        handle = open(self.mappingFileName, "w")
        handle.write("read1\t0\tchr1\t1\t30\t20M\t*\t0\t0\tAAAAAAAAAAAAAAAAAAAA\tAAAAAAAAAAAAAAAAAAAA\tNM:i:0\n")
        handle.write("read2\t0\tchr2\t1\t30\t20M\t*\t0\t0\tCCCCCCCCCCCCCCCCCCCC\tAAAAAAAAAAAAAAAAAAAA\tNM:i:0\n")
        handle.write("read2\t0\tchr3\t1\t30\t20M\t*\t0\t0\tCCCCCCCCCCCCCCCCCCCC\tAAAAAAAAAAAAAAAAAAAA\tNM:i:0\n")
        handle.close()
        analyzer = MapperAnalyzer(0)
        analyzer.setMappingFile(self.mappingFileName, "sam")
        analyzer.setSequenceFile(self.readsFileName, "fastq")
        analyzer.setOutputFile(self.outputFileName, "S-MART")
        analyzer.setMaxMappings(1)
        analyzer.mergeExons(True)
        analyzer.analyze()

        parser = GffParser(self.outputFileName)
        self.assertEqual(parser.getNbTranscripts(), 1)
        for transcript in parser.getIterator():
            self.assertEqual(transcript.getName(), "read1")
            self.assertEqual(transcript.getChromosome(), "chr1")
            self.assertEqual(transcript.getStart(), 1)
            self.assertEqual(transcript.getEnd(), 20)
            self.assertEqual(transcript.getDirection(), 1)
            
        
if __name__ == "__main__":
    unittest.main()

