from datetime import datetime, timedelta

from django.test import TestCase, Client

from authentication.models import ExtendedUser
from inventory.models import Event, Container, Item
from mail.models import Email, EmailAttachment
from tickets.models import IssueThread, StateChange, Comment, ItemRelation
from django.contrib.auth.models import Permission
from knox.models import AuthToken

from base64 import b64encode


class IssueItemMatchApiTest(TestCase):

    def setUp(self):
        super().setUp()
        self.user = ExtendedUser.objects.create_user('testuser', 'test', 'test')
        self.user.user_permissions.add(*Permission.objects.all())
        self.user.save()
        self.event = Event.objects.create(slug='evt')
        self.box = Container.objects.create(name='box1')
        self.item = Item.objects.create(container=self.box, description="foo", event=self.event)
        self.token = AuthToken.objects.create(user=self.user)
        self.client = Client(headers={'Authorization': 'Token ' + self.token[1]})
        now = datetime.now()
        self.issue = IssueThread.objects.create(
            name="test issue",
            event=self.event,
        )
        self.mail1 = Email.objects.create(
            subject='test',
            body='test',
            sender='test',
            recipient='test',
            issue_thread=self.issue,
            timestamp=now,
        )
        self.comment = Comment.objects.create(
            issue_thread=self.issue,
            comment="test",
            timestamp=now + timedelta(seconds=3),
        )
        self.match = ItemRelation.objects.create(
            issue_thread=self.issue,
            item=self.item,
            timestamp=now + timedelta(seconds=5),
        )

    def test_issues(self):
        response = self.client.get('/api/2/tickets/')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(response.json()), 1)
        self.assertEqual(response.json()[0]['id'], self.issue.id)
        self.assertEqual(response.json()[0]['name'], "test issue")
        self.assertEqual(response.json()[0]['state'], "pending_new")
        self.assertEqual(response.json()[0]['event'], "evt")
        self.assertEqual(response.json()[0]['assigned_to'], None)
        self.assertEqual(response.json()[0]['uuid'], self.issue.uuid)
        self.assertEqual(response.json()[0]['last_activity'], self.match.timestamp.strftime('%Y-%m-%dT%H:%M:%S.%fZ'))
        self.assertEqual(len(response.json()[0]['timeline']), 4)
        self.assertEqual(response.json()[0]['timeline'][0]['type'], 'state')
        self.assertEqual(response.json()[0]['timeline'][1]['type'], 'mail')
        self.assertEqual(response.json()[0]['timeline'][2]['type'], 'comment')
        self.assertEqual(response.json()[0]['timeline'][1]['id'], self.mail1.id)
        self.assertEqual(response.json()[0]['timeline'][2]['id'], self.comment.id)
        self.assertEqual(response.json()[0]['timeline'][0]['state'], 'pending_new')
        self.assertEqual(response.json()[0]['timeline'][1]['sender'], 'test')
        self.assertEqual(response.json()[0]['timeline'][1]['recipient'], 'test')
        self.assertEqual(response.json()[0]['timeline'][1]['subject'], 'test')
        self.assertEqual(response.json()[0]['timeline'][1]['body'], 'test')
        self.assertEqual(response.json()[0]['timeline'][1]['timestamp'],
                         self.mail1.timestamp.strftime('%Y-%m-%dT%H:%M:%S.%fZ'))
        self.assertEqual(response.json()[0]['timeline'][2]['comment'], 'test')
        self.assertEqual(response.json()[0]['timeline'][2]['timestamp'],
                         self.comment.timestamp.strftime('%Y-%m-%dT%H:%M:%S.%fZ'))
        self.assertEqual(response.json()[0]['timeline'][3]['status'], 'possible')
        self.assertEqual(response.json()[0]['timeline'][3]['timestamp'],
                         self.match.timestamp.strftime('%Y-%m-%dT%H:%M:%S.%fZ'))
        self.assertEqual(response.json()[0]['timeline'][3]['item']['description'], "foo")
        self.assertEqual(response.json()[0]['timeline'][3]['item']['event'], "evt")
        self.assertEqual(response.json()[0]['timeline'][3]['item']['box'], "box1")
        self.assertEqual(response.json()[0]['related_items'][0]['description'], "foo")
        self.assertEqual(response.json()[0]['related_items'][0]['event'], "evt")
        self.assertEqual(response.json()[0]['related_items'][0]['box'], "box1")

    def test_members(self):
        response = self.client.get(f'/api/2/{self.event.slug}/item/')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(response.json()), 1)
        self.assertEqual(response.json()[0]['id'], self.item.id)
        self.assertEqual(response.json()[0]['description'], 'foo')
        self.assertEqual(response.json()[0]['box'], 'box1')
        self.assertEqual(response.json()[0]['cid'], self.box.id)
        self.assertEqual(response.json()[0]['file'], None)
        self.assertEqual(response.json()[0]['returned'], False)
        self.assertEqual(response.json()[0]['event'], self.event.slug)
        self.assertEqual(len(response.json()[0]['related_issues']), 1)
        self.assertEqual(response.json()[0]['related_issues'][0]['id'], self.issue.id)
        self.assertEqual(response.json()[0]['related_issues'][0]['name'], "test issue")

    def test_add_match(self):
        response = self.client.get('/api/2/matches/')
        self.assertEqual(1, len(response.json()))
        item = Item.objects.create(container=self.box, event=self.event, description='1')
        issue = IssueThread.objects.create(name="test issue", event=self.event)

        response = self.client.post(f'/api/2/matches/',
                                    {'item': item.id, 'issue_thread': issue.id},
                                    content_type='application/json')
        self.assertEqual(response.status_code, 201)

        response = self.client.get('/api/2/matches/')
        self.assertEqual(2, len(response.json()))

        response = self.client.get('/api/2/tickets/')
        self.assertEqual(4, len(response.json()[0]['timeline']))
        self.assertEqual('item_relation', response.json()[0]['timeline'][3]['type'])
        self.assertEqual('possible', response.json()[0]['timeline'][3]['status'])
        self.assertEqual(1, len(response.json()[0]['related_items']))

    def test_change_match_state(self):
        response = self.client.get('/api/2/matches/')
        self.assertEqual(1, len(response.json()))

        response = self.client.get('/api/2/tickets/')
        self.assertEqual(4, len(response.json()[0]['timeline']))
        self.assertEqual('item_relation', response.json()[0]['timeline'][3]['type'])
        self.assertEqual('possible', response.json()[0]['timeline'][3]['status'])
        self.assertEqual(1, len(response.json()[0]['related_items']))

        response = self.client.post(f'/api/2/matches/',
                                    {'item': self.item.id, 'issue_thread': self.issue.id, 'status': 'confirmed'},
                                    content_type='application/json')
        self.assertEqual(response.status_code, 201)
        self.assertEqual(response.json()['status'], 'confirmed')
        self.assertEqual(response.json()['id'], 2)

        response = self.client.get('/api/2/matches/')
        self.assertEqual(2, len(response.json()))

        response = self.client.get('/api/2/tickets/')
        self.assertEqual(5, len(response.json()[0]['timeline']))
        self.assertEqual('item_relation', response.json()[0]['timeline'][3]['type'])
        self.assertEqual('possible', response.json()[0]['timeline'][3]['status'])
        self.assertEqual('item_relation', response.json()[0]['timeline'][4]['type'])
        self.assertEqual('confirmed', response.json()[0]['timeline'][4]['status'])
        self.assertEqual(1, len(response.json()[0]['related_items']))