import json
import os
from datetime import datetime
from mock import patch

from django.utils import timezone
from django.conf import settings
from django.test.utils import override_settings
from django.test import SimpleTestCase

from bluebottle.analytics import signals, utils
from bluebottle.analytics.tasks import queue_analytics_record
from bluebottle.analytics.backends import InfluxExporter, FileExporter, _convert_timestamp

from .common import FakeModel, FakeModelTwo


def do_nothing(**kwargs):
    pass


@override_settings(ANALYTICS_ENABLED=True)
class TestAnalyticsQueue(SimpleTestCase):
    @patch.object(InfluxExporter, 'process')
    def test_tags_generation(self, mock_process):
        tags = {
            'tenant': 'test',
            'type': 'order'
        }
        fields = {
            'amount': 100
        }

        timestamp = timezone.now()
        queue_analytics_record(timestamp=timestamp, tags=tags, fields=fields)
        mock_process.assert_called_with(timestamp, tags, fields)

    def test_convert_time_to_microseconds(self):
        timestamp = datetime(2016, 12, 31, 23, 59, 59, 123456)
        result = _convert_timestamp(timestamp)
        self.assertEqual(result, 1483228799123456)


@override_settings(ANALYTICS_ENABLED=True)
@override_settings(ANALYTICS_BACKENDS={
    'file': {
        'handler_class': 'bluebottle.analytics.backends.FileExporter',
        'base_dir': os.path.join(settings.PROJECT_ROOT, 'logs', 'analytics'),
        'measurement': 'saas',
    }
})
class TestFileAnalyticsQueue(SimpleTestCase):
    def setUp(self):
        super(TestFileAnalyticsQueue, self).setUp()

        self.tags = {
            'tenant': 'test',
            'type': 'order'
        }

        self.fields = {
            'amount': 100
        }

        base_dir = os.path.join(settings.PROJECT_ROOT, 'logs', 'analytics')
        self.log_dir = os.path.join(base_dir, self.tags['tenant'])

    @patch.object(FileExporter, 'process')
    def test_file_exporter(self, mock_process):
        timestamp = timezone.now()
        queue_analytics_record(timestamp=timestamp, tags=self.tags, fields=self.fields)
        mock_process.assert_called_with(timestamp, self.tags, self.fields)

    def test_log_file_generated(self):
        timestamp = datetime(2016, 12, 31, 23, 59, 59, 123456)
        queue_analytics_record(timestamp=timestamp, tags=self.tags, fields=self.fields)

        log_path = os.path.join(self.log_dir, '{}.log'.format(timestamp.strftime('%Y-%m-%d')))
        self.assertTrue(os.path.exists(log_path))

        # Get last line from log
        with open(log_path) as infile:
            for line in infile:
                if not line.strip('\n'):
                    continue
                last_line = line

        json_logs = json.loads(last_line)
        log = json_logs[0]
        self.assertEqual(len(json_logs), 1)
        self.assertEqual(log['fields'], self.fields)
        self.assertEqual(log['tags'], self.tags)
        self.assertEqual(log['time'], 1483228799123456)
        self.assertEqual(log['measurement'], 'saas')


@override_settings(ANALYTICS_ENABLED=True, CELERY_RESULT_BACKEND='amqp')
class TestAnalyticsSignalWithCelery(SimpleTestCase):
    @patch.object(utils.connection, 'schema_name', 'test')
    def test_delay_called(self):
        tags = {
            'tenant': 'test',
            'type': 'fake'
        }
        fields = {}

        with patch('bluebottle.analytics.tasks.queue_analytics_record.delay') as mock_delay:
            signals.post_save_analytics(None, FakeModel(), **{'created': True})

            args, kwargs = mock_delay.call_args
            self.assertEqual(kwargs['tags'], tags)
            self.assertEqual(kwargs['fields'], fields)


@override_settings(ANALYTICS_ENABLED=True)
class TestAnalyticsPostSave(SimpleTestCase):
    @patch.object(utils.connection, 'schema_name', 'test')
    def test_metric_type(self):
        tags = {
            'tenant': 'test',
            'type': 'fake_model_two'
        }

        with patch('bluebottle.analytics.utils.queue_analytics_record') as mock_queue:
            mock_queue.side_effect = do_nothing
            signals.post_save_analytics(None, FakeModelTwo(), **{'created': True})

            args, kwargs = mock_queue.call_args
            self.assertEqual(kwargs['tags'], tags)

@@ -48,31 +48,8 @@
 time
-%0Afrom mock import patch
 %0A%0Afr
@@ -58,29 +58,28 @@
  django.
-utils
+conf
  import 
 timezone
@@ -70,24 +70,24 @@
  import 
-timezone
+settings
 %0Afrom dj
@@ -87,36 +87,36 @@
 from django.
-conf
+test
  import 
 settings%0Afro
@@ -99,32 +99,38 @@
 test import 
-settings
+SimpleTestCase
 %0Afrom django
@@ -174,36 +174,37 @@
 from django.
-test
+utils
  import 
 SimpleTestCa
@@ -191,30 +191,47 @@
  import 
-SimpleTestCase
+timezone%0Afrom mock import patch
 %0A%0Afrom b
@@ -298,20 +298,23 @@
 alytics.
-task
+backend
 s import
@@ -314,38 +314,28 @@
  import 
-queue_analytics_record
+FileExporter
 %0Afrom bl
@@ -345,39 +345,36 @@
 ottle.analytics.
-backend
+task
 s import InfluxE
@@ -370,57 +370,30 @@
 ort 
-InfluxExporter, FileExporter, _convert_timestamp%0A
+queue_analytics_record
 %0Afro
@@ -476,720 +476,8 @@
 s%0A%0A%0A
-@override_settings(ANALYTICS_ENABLED=True)%0Aclass TestAnalyticsQueue(SimpleTestCase):%0A    @patch.object(InfluxExporter, 'process')%0A    def test_tags_generation(self, mock_process):%0A        tags = %7B%0A            'tenant': 'test',%0A            'type': 'order'%0A        %7D%0A        fields = %7B%0A            'amount': 100%0A        %7D%0A%0A        timestamp = timezone.now()%0A        queue_analytics_record(timestamp=timestamp, tags=tags, fields=fields)%0A        mock_process.assert_called_with(timestamp, tags, fields)%0A%0A    def test_convert_time_to_microseconds(self):%0A        timestamp = datetime(2016, 12, 31, 23, 59, 59, 123456)%0A        result = _convert_timestamp(timestamp)%0A        self.assertEqual(result, 1483228799123456)%0A%0A%0A
 @ove

Remove obsolete test