#!/usr/bin/env python3
import os
import sys
import unittest

lib_path = os.path.abspath('..')
sys.path.append(lib_path)

from epac.ete2 import SeqGroup
from epac.taxonomy_util import Taxonomy, TaxCode
from epac.config import EpacConfig
from epac.json_util import EpaJsonParser, RefJsonParser, RefJsonBuilder
from epac.ete2 import Tree

class JsonTests(unittest.TestCase):

    def setUp(self):
        self.cfg = EpacConfig()
        self.testfile_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "testfiles")
    
    def test_jplace_read(self):
        jplace_fname = os.path.join(self.testfile_dir, "test.jplace")
        parser = EpaJsonParser(jplace_fname)
        self.assertEqual(parser.get_raxml_version(), "8.2.3")
        t = Tree(parser.get_tree())
        t_len = len(t)
        self.assertEqual(t_len, 32)
        self.assertEqual(len(parser.get_placement()), 6)
        for p in parser.get_placement():
            self.assertFalse(p["n"][0] in t) 
            self.assertTrue(len(p["p"]) > 0) 
            for edge in p["p"]:
                branch = int(edge[0])
                lh = edge[1]
                lhw = edge[2]
                self.assertTrue(branch >= 0 and branch < (t_len * 2 - 3)) 
                self.assertTrue(lhw >= 0.0 and lhw <= 1.0) 
        
    def test_refjson_read(self):
        versions = ["1.4", "1.5", "1.6"]
        for ver in versions:
            ref_fname = os.path.join(self.testfile_dir, "test.refjson.v%s" % ver)
            parser = RefJsonParser(ref_fname)
            valid, errors = parser.validate()
            self.assertTrue(valid) 
            self.assertEqual(parser.get_version(), ver) 
            
        jplace_fname = os.path.join(self.testfile_dir, "test.jplace")
        parser = RefJsonParser(jplace_fname) 
        valid, errors = parser.validate()
        self.assertFalse(valid) 
        
        tax_fname = os.path.join(self.testfile_dir, "test.tax")
        with self.assertRaises(ValueError):
            parser = RefJsonParser(tax_fname)            
        
        
if __name__ == '__main__':
    unittest.main()
