import unittest
import os
from SMART.Java.Python.GetRandomSubset import GetRandomSubset
from commons.core.parsing.BedParser import BedParser
from commons.core.parsing.GffParser import GffParser

class Test_F_GetRandomSubset(unittest.TestCase):

    def setUp(self):
        self._inputFileName = "inputFileTest.bed"
        self._writeInputFile()
        self._outputFileName = "output.gff3"
        
    def tearDown(self):
        os.remove(self._inputFileName)
        os.remove(self._outputFileName)

    def test_run_simple(self):
        nbElements = 2
        inputTranscripts = []
        parser = BedParser(self._inputFileName, 0)
        for transcript in parser.getIterator():
            inputTranscripts.append(transcript)
        grs = GetRandomSubset(0)
        grs.setInputFile(self._inputFileName, "bed")
        grs.setNumber(nbElements, None)
        grs.setOutputFile(self._outputFileName)
        grs.run()
        outputTranscripts = []
        parser = GffParser(self._outputFileName, 0)
        for transcript in parser.getIterator():
            outputTranscripts.append(transcript)
        self.assertEqual(len(outputTranscripts), nbElements)
        for outputTranscript in outputTranscripts:
            for inputTranscript in inputTranscripts:
                if outputTranscript.getChromosome() == inputTranscript.getChromosome() and outputTranscript.getDirection() == inputTranscript.getDirection() and outputTranscript.getStart() == inputTranscript.getStart() and outputTranscript.getEnd() == inputTranscript.getEnd() and outputTranscript.getName() == inputTranscript.getName():
                    break
            else:
                self.fail()

    def _writeInputFile(self):
        f = open(self._inputFileName, "w")
        f.write("arm_X\t10000100\t10000200\ttest1.1\t100\t+\t10000100\t10000200\t0\t1\t100,\t0,\n")
        f.write("arm_X\t10000100\t10000200\ttest1.2\t100\t-\t10000100\t10000200\t0\t1\t100,\t0,\n")
        f.write("arm_2R\t10000100\t10000200\ttest1.3\t100\t+\t10000100\t10000200\t0\t1\t100,\t0,\n")
        f.write("arm_X\t10000000\t10000100\ttest1.4\t100\t+\t10000000\t10000100\t0\t1\t100,\t0,\n")
        f.write("arm_X\t10000200\t10000300\ttest1.5\t100\t+\t10000200\t10000300\t0\t1\t100,\t0,\n")
        f.write("arm_X\t9999900\t9999950\ttest1.6\t100\t+\t9999900\t9999950\t0\t1\t50,\t0,\n")
        f.write("arm_X\t10000000\t10000050\ttest1.7\t100\t-\t10000000\t10000050\t0\t1\t50,\t0,\n")
        f.close()
        
                

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