import datetime
from pathlib import Path
import unittest

from pmsco.schedule import JobSchedule, SlurmSchedule, PsiRaSchedule


class TestSlurmSchedule(unittest.TestCase):
    def test_parse_timedelta(self):
        """
                @param td:
            str: [days-]hours[:minutes[:seconds]]
            dict: days, hours, minutes, seconds - at least one needs to be defined. values must be numeric.
            datetime.timedelta - native type
        @return: datetime.timedelta

        """

        input = "1-15:20:23"
        expected = datetime.timedelta(days=1, hours=15, minutes=20, seconds=23)
        self.assertEqual(SlurmSchedule.parse_timedelta(input), expected)
        input = {"days": 1, "hours": 15, "minutes": 20, "seconds": 23}
        self.assertEqual(SlurmSchedule.parse_timedelta(input), expected)
        input = {"days": "1", "hours": "15", "minutes": "20", "seconds": "23"}
        self.assertEqual(SlurmSchedule.parse_timedelta(input), expected)

        input = "15"
        expected = datetime.timedelta(hours=15)
        self.assertEqual(SlurmSchedule.parse_timedelta(input), expected)
        input = {"hours": 15}
        self.assertEqual(SlurmSchedule.parse_timedelta(input), expected)

        input = "12:00"
        expected = datetime.timedelta(hours=12, minutes=0)
        self.assertEqual(SlurmSchedule.parse_timedelta(input), expected)

        input = "15:20:23"
        expected = datetime.timedelta(hours=15, minutes=20, seconds=23)
        self.assertEqual(SlurmSchedule.parse_timedelta(input), expected)

        input = "1-15"
        expected = datetime.timedelta(days=1, hours=15)
        self.assertEqual(SlurmSchedule.parse_timedelta(input), expected)

        input = "1-15:20"
        expected = datetime.timedelta(days=1, hours=15, minutes=20)
        self.assertEqual(SlurmSchedule.parse_timedelta(input), expected)

        input = {"days": 1}
        expected = datetime.timedelta(days=1)
        self.assertEqual(SlurmSchedule.parse_timedelta(input), expected)
        input = "24:00"
        self.assertEqual(SlurmSchedule.parse_timedelta(input), expected)

        expected = datetime.timedelta(days=2)
        input = "48:00"
        self.assertEqual(SlurmSchedule.parse_timedelta(input), expected)

        input = {"minutes": 20}
        expected = datetime.timedelta(minutes=20)
        self.assertEqual(SlurmSchedule.parse_timedelta(input), expected)

        input = {"seconds": 23}
        expected = datetime.timedelta(seconds=23)
        self.assertEqual(SlurmSchedule.parse_timedelta(input), expected)

    def test_detect_env(self):
        result = SlurmSchedule.detect_env()
        self.assertTrue(result, "undetectable environment")
        for key, value in result.items():
            self.assertTrue(key in {"conda", "venv", "system"}, "unknown environment type")
            self.assertTrue(Path(value).is_dir())


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