import unittest
import logging
import os
import sys
import argparse


from toolbox_scs.util.data_access import (
    find_run_dir,
    )
from toolbox_scs.util.exceptions import ToolBoxPathError

suites = {"ed-extensions": (
                "test_rundir1",
                "test_rundir2",
                "test_rundir3",
                )
          }


def list_suites():
    print("""\nPossible test suites:\n-------------------------""")
    for key in suites:
        print(key)
    print("-------------------------\n")


class TestDataAccess(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        pass

    @classmethod
    def tearDownClass(cls):
        pass

    def setUp(self):
        pass

    def tearDown(self):
        pass

    def test_rundir1(self):
        Proposal = 2212
        Run = 235
        Dir = find_run_dir(Proposal, Run)
        self.assertEqual(Dir,
                "/gpfs/exfel/exp/SCS/201901/p002212/raw/r0235")

    def test_rundir2(self):
        Proposal = 23678
        Run = 235
        with self.assertRaises(Exception) as cm:
            find_run_dir(Proposal, Run)
        exp = cm.exception
        self.assertEqual(str(exp), "Couldn't find proposal dir for 'p023678'")
    
    def test_rundir3(self):
        Proposal = 2212
        Run = 800
        with self.assertRaises(ToolBoxPathError) as cm:
            find_run_dir(Proposal, Run)
        exp_msg = cm.exception.message
        print(exp_msg)
        path = f'/gpfs/exfel/exp/SCS/201901/p00{Proposal}/raw/r0{Run}'
        err_msg = f"Invalid path: {path}. " \
                  "The constructed path does not exist."
        self.assertEqual(exp_msg, err_msg)


def suite(*tests):
    suite = unittest.TestSuite()
    for test in tests:
        suite.addTest(TestDataAccess(test))
    return suite


def main(*cliargs):
    logging.basicConfig(level=logging.DEBUG)
    log_root = logging.getLogger(__name__)
    try:
        for test_suite in cliargs:
            if test_suite in suites:
                runner = unittest.TextTestRunner(verbosity=2)
                runner.run(suite(*suites[test_suite]))
            else:
                log_root.warning(
                    "Unknown suite: '{}'".format(test_suite))
                pass
    except Exception as err:
        log_root.error("Unecpected error: {}".format(err),
                  exc_info=True)
        pass






if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--list-suites',
                action='store_true',
                help='list possible test suites')
    parser.add_argument('--run-suites', metavar='S',
                nargs='+', action='store',
                help='a list of valid test suites')
    args = parser.parse_args()
    
    if args.list_suites:
        list_suites()

    if args.run_suites:
        main(*args.run_suites)