# -*- coding: utf-8 -*-
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.

import os

from django.contrib.auth import get_user_model
from django.core.files import File
from django.core.files.base import ContentFile
from django.core.files.storage import default_storage
from django.test import TestCase

from .models import VideoInfo
from .tasks import encode


class EncodeTests(TestCase):
    def setUp(self):
        User = get_user_model()
        user = User(username='test', email='test@example.com')
        user.set_password('123')
        user.save()

        self.info = VideoInfo.objects.create(user=user)

    def test_1080_all_format(self):
        path = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                            'clip_1080p.mp4')
        with open(path, 'rb') as m:
            f = File(m)
            default_storage.save(self.info.ref, f)
        encode(self.info.ref)
        self.info.refresh_from_db()
        self.assertEqual(10, self.info.video_set.count())
        for v in self.info.video_set.all():
            self.assertIsNotNone(v.video)

    def test_720_all_but_one_format(self):
        path = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                            'clip_720p.mp4')
        with open(path, 'rb') as m:
            f = File(m)
            default_storage.save(self.info.ref, f)
        encode(self.info.ref)
        self.info.refresh_from_db()
        self.assertEqual(8, self.info.video_set.count())
        for v in self.info.video_set.all():
            self.assertIsNotNone(v.video)

    def test_invalid_file(self):
        f = ContentFile(b'error')
        default_storage.save(self.info.ref, f)
        encode(self.info.ref)
        self.info.refresh_from_db()
        self.assertTrue(self.info.probe_error)


class VideoInfoTests(TestCase):
    def setUp(self):
        # Create a user to own test videos.
        User = get_user_model()
        user = User(username='test', email='test@example.com')
        user.set_password('123')
        user.save()
        self.user = user

    def test_videoinfo_ref_gen(self):
        VideoInfo.objects.create(user=self.user)
        VideoInfo.objects.create(user=self.user)

    def test_videoinfo_ref_override(self):
        info = VideoInfo(user=self.user, ref='12345678')
        info.save(override_ref=True)
        self.assertEqual('12345678', info.ref)
