import random
import time
import datetime

from django.test import TestCase
from gm_types.user_hierarchy import EventType

from user_hierarchy.views import get_user_growth, push_event
from .models import UserEventLog
from .tasks import process_user_add_value


class MimasTest(TestCase):
    def setUp(self):
        UserEventLog.objects.create(
        user_id=22,
        event_type=EventType.BINDPHONE,
        trigger_time=datetime.datetime.now(),
        value=20,
        )
        process_user_add_value(22)

    @property
    def _args(self):
        return {
            'event_type': None,
            'trigger_time': time.time(),
            'user_id': 22,
            'item_id': None,
            'pre_payment': 200,
        }

    def test_push_event(self):
        self.assertRaises(NotImplementedError, push_event, **self._args)
        # test commet diary
        args = self._args
        args['event_type'] = EventType.COMMENTDIARY
        time = 11
        for i in range(time):
            _v = push_event(**args)
            self.assertIsInstance(_v, int)
        v5 = UserEventLog.objects.filter(user_id=22, event_type=EventType.COMMENTDIARY, value=5).exists()
        v0 = UserEventLog.objects.filter(user_id=22, event_type=EventType.COMMENTDIARY, value=0).exists()
        self.assertTrue(v5)
        self.assertTrue(v0)

        # test buy service
        args = self._args
        args['event_type'] = EventType.BUYSERVICE
        _v = push_event(**args)
        self.assertIsInstance(_v, int)
        value = UserEventLog.objects.get(user_id=22, event_type=EventType.BUYSERVICE).value
        self.assertTrue(bool(value > 0 and value < 300))

        # test all
        for event_type in EventType:
            _e = event_type[0]
            args = self._args
            args['event_type'] = _e
            _v = push_event(**args)
            self.assertIsInstance(_v, int)

    def test_get_user_growth(self):
        user_id = random.randint(1, 999999999)
        result = get_user_growth(user_id)
        self.assertIsInstance(result, dict)

        # test user id 22
        result = get_user_growth(22)
        self.assertIsInstance(result, dict)
        self.assertTrue(result['value'] > 0)
