from datetime import datetime, timedelta, timezone
import unittest

from . import mixin


class IotApiTest(mixin.AioMixin, unittest.IsolatedAsyncioTestCase):
    async def test_01(self):
        resp = await self.api.vulnerability(pagelength=0)
        self.assertEqual(resp.status, 400)

        resp = await self.api.vulnerability(groupby='x-invalid')
        self.assertEqual(resp.status, 400)

    async def test_02(self):
        resp = await self.api.vulnerability(groupby='device',
                                            pagelength=1)
        self.assertEqual(resp.status, 200)
        x = await resp.json()
        self.assertIn(x['total'], (0, 1))
        self.assertIn(len(x['items']), (0, 1))

    async def test_03(self):
        for groupby in (None, 'vulnerability'):
            # pagelength ignored
            resp = await self.api.vulnerability(groupby=groupby,
                                                pagelength=1)
            self.assertEqual(resp.status, 200)
            x = await resp.json()
            self.assertGreaterEqual(x['total'], 0)
            self.assertGreaterEqual(len(x['items']['items']), 0)

    async def test_04(self):
        total = 0
        async for ok, x in self.api.vulnerabilities_all(groupby='device'):
            self.assertTrue(ok)
            total += 1
            if total > 1050:
                break

    async def test_05(self):
        total = 0
        async for ok, x in self.api.vulnerabilities_all(
                groupby='vulnerability'):
            self.assertTrue(ok)
            if 'Confirmed' in x['data']:
                total += 1
            if 'Potential' in x['data']:
                total += 1

        confirmed = 0
        async for ok, x in self.api.vulnerabilities_all(
                groupby='vulnerability',
                query_string={'status': 'Confirmed'}):
            self.assertTrue(ok)
            self.assertIn('Confirmed', x['data'])
            self.assertNotIn('Potential', x['data'])
            confirmed += 1

        potential = 0
        async for ok, x in self.api.vulnerabilities_all(
                groupby='vulnerability',
                query_string={'status': 'Potential'}):
            self.assertTrue(ok)
            self.assertIn('Potential', x['data'])
            self.assertNotIn('Confirmed', x['data'])
            potential += 1

        self.assertEqual(total, confirmed+potential,
                         'vulnerability total != Confirmed+Potential')

    async def test_06(self):
        d = datetime.now(tz=timezone.utc) + timedelta(seconds=10)
        stime = d.strftime('%Y-%m-%dT%H:%M:%SZ')
        resp = await self.api.vulnerability(stime=stime)
        self.assertEqual(resp.status, 200)
        x = await resp.json()
        t = await resp.text()
        msg = 'vulnerabilities in future stime %s: ' % stime
        msg += t
        self.assertEqual(x['total'], 0, msg)
        self.assertEqual(len(x['items']['items']), 0, msg)
