import unittest
import os
from commons.core.parsing.GffParser import GffParser
from SMART.Java.Python.getRandomRegions import RandomRegionsGenerator

MIN_SIZE = 36
MAX_SIZE = 100
CHR      = "chr1"
CHR_SIZE = 1000000
NB_READS = 1000

class Test_F_getRandomRegions(unittest.TestCase):

    def setUp(self):
        self._outputFileName = 'output.gff3'
        
    def tearDown(self):
        for fileName in [self._outputFileName]:
            if os.path.exists(fileName):
                os.remove(fileName)
        
    def test_simple(self):
        iRR = RandomRegionsGenerator(0)
        iRR.setMinSize(MIN_SIZE)
        iRR.setMaxSize(MAX_SIZE)
        iRR.setGenomeSize(CHR_SIZE)
        iRR.setChromosomeName(CHR)
        iRR.setStrands(False)
        iRR.setNumber(NB_READS)
        iRR.setOutputFile(self._outputFileName)
        iRR.run()
        parser = GffParser(self._outputFileName, 0)
        starts = set()
        self.assertTrue(parser.getNbTranscripts(), CHR_SIZE)
        for transcript in parser.getIterator():
            start      = transcript.getStart()
            end        = transcript.getEnd()
            size       = transcript.getSize()
            chromosome = transcript.getChromosome()
            strand     = transcript.getDirection()
            self.assertTrue(start not in starts)
            self.assertTrue(start >= 1)
            self.assertTrue(end <= CHR_SIZE)
            self.assertEquals(chromosome, CHR)
            self.assertEquals(strand, 1)
            starts.add(start)

    def test_both_strands(self):
        iRR = RandomRegionsGenerator(0)
        iRR.setMinSize(MIN_SIZE)
        iRR.setMaxSize(MAX_SIZE)
        iRR.setGenomeSize(CHR_SIZE)
        iRR.setChromosomeName(CHR)
        iRR.setStrands(True)
        iRR.setNumber(NB_READS)
        iRR.setOutputFile(self._outputFileName)
        iRR.run()
        parser = GffParser(self._outputFileName, 0)
        strands = set()
        for transcript in parser.getIterator():
            strands.add(transcript.getDirection())
        self.assertTrue(1 in strands)
        self.assertTrue(-1 in strands)
        
if __name__ == "__main__":
    unittest.main()
