import datetime

from osf_tests.factories import PreprintFactory, PreprintProviderFactory
from osf.models import PreprintService
import mock
import pytest
import pytz
import requests

from scripts.analytics.preprint_summary import PreprintSummary


@pytest.fixture()
def preprint_provider():
    return PreprintProviderFactory(name='Test 1')

@pytest.fixture()
def preprint(preprint_provider):
    return PreprintFactory._build(PreprintService, provider=preprint_provider)


@pytest.fixture()
def yesterday_at_midnight():
    return datetime.datetime.utcnow().replace(hour=0,
                                              minute=0,
                                              second=0,
                                              microsecond=0) - datetime.timedelta(days=1)


@pytest.fixture()
def yesterday_right_before_today():
    return datetime.datetime.utcnow().replace(hour=23,
                                              minute=59,
                                              second=59) - datetime.timedelta(days=1)


@pytest.fixture()
def my_birthday_at_midnight():
    return datetime.datetime(1991, 9, 25, 0)

pytestmark = pytest.mark.django_db


@pytest.mark.parametrize("date", [yesterday_at_midnight(), yesterday_right_before_today(), my_birthday_at_midnight()])
class TestPreprintCount:

    def test_get_preprint_count(self, preprint, date):

        requests.post = mock.MagicMock()
        resp = requests.Response()
        resp._content = '{"hits" : {"total" : 1}}'
        requests.post.return_value = resp

        field = PreprintService._meta.get_field('date_created')
        field.auto_now_add = False  # We have to fudge the time because Keen doesn't allow same day queries.

        preprint.date_created = date - datetime.timedelta(hours=1)
        preprint.save()

        field.auto_now_add = True
        results = PreprintSummary().get_events(date.date())

        assert len(results) == 1

        data = results[0]
        assert data['provider']['name'] == 'Test 1'
        assert data['provider']['total'] == 1


@@ -175,16 +175,50 @@
 requests
+%0Afrom django.utils import timezone
 %0A%0Afrom s
@@ -560,37 +560,25 @@
  return 
-datetime.datetime.utc
+timezone.
 now().re
@@ -621,36 +621,24 @@
             
-           
- 
 minute=0,%0A  
@@ -631,36 +631,24 @@
   minute=0,%0A
-            
             
@@ -675,36 +675,24 @@
   second=0,%0A
-            
             
@@ -828,29 +828,17 @@
 urn 
-datetime.datetime.utc
+timezone.
 now(
@@ -894,43 +894,19 @@
     
-            minute=59,%0A            
+minute=59,%0A
     
@@ -1069,16 +1069,33 @@
 9, 25, 0
+, tzinfo=pytz.utc
 )%0A%0Apytes
@@ -1155,14 +1155,14 @@
 ize(
-%22
+'
 date
-%22
+'
 , %5By

add timezone info and flake fix.