"""This module contains the test cases for the views of the api"""

import json
import os
import tempfile

from django.conf import settings
from django.core.urlresolvers import reverse

from mtp.apps.themes.models import Theme

from .test_cases import APITestCase


class UploadAPIViewTestCase(APITestCase):
    """Test cases for the ``upload`` api route"""

    def test_upload_post(self):
        """Test that the ``upload`` route work"""

        file_content = 'file_content'.encode('utf-8')

        fp = tempfile.NamedTemporaryFile()
        fp.write(file_content)
        fp.seek(0)

        params = {
            'post_params_1': 'content1',
            'post_params_2': 'content2',
            'post_params_3': 'content3',
        }
        files = {
            'post_file_1': fp
        }

        folder_name = 'test'
        upload_url = reverse('api:upload_post', kwargs={'folder_name': folder_name})
        upload_data = dict(list(params.items()) + list(files.items()))

        response_raw = self.client.post(upload_url, upload_data)
        response = json.loads(response_raw.content.decode('utf-8'))

        test_folder = os.path.join(settings.UPLOAD_ROOT, folder_name)
        test_folder = os.path.join(test_folder, response['timestamp'])

        for key in params.keys():
            filename = os.path.join(test_folder, key)
            self.assertTrue(os.path.exists(filename))
            fp_test = open(filename)
            content = fp_test.read()
            self.assertEqual(content, params[key])

        for key in files.keys():
            filename = os.path.join(test_folder, key)
            self.assertTrue(os.path.exists(filename))
            fp_test = open(filename)
            content = fp_test.read()
            self.assertEqual(content, file_content.decode('utf-8'))

        # Cleanup
        fp.close()


class DownloadsAPITestCase(APITestCase):
    """Test cases for the ``downloads`` api route"""

    @classmethod
    def setUpTestData(cls):
        """Set up the test data"""

        super().setUpTestData()

        cls.downloads_url = reverse('api:downloads', kwargs={'file_id': 'wtf-wtf'})

    def test_downloads_should_work(self):
        """Test that the ``downloads`` route work"""

        response = self.client.get(self.downloads_url)

        self.assertEqual(response.status_code, 200)


class GlobalSettingsViewTestCase(APITestCase):
    """Test cases for the ``client_settings`` view"""

    def test_global_settings_should_work(self):
        """Test that the ``client_settings`` output is correct"""

        response = self.client.post(
            reverse('client_settings'),
            {
                'app_version': 12345
            }
        )

        # The route work
        self.assertEqual(response.status_code, 200)

        default_theme = Theme.objects.non_deleted().filter(default=True).first()
        default_theme_pk = default_theme.pk if default_theme else None

        # The output is correct
        self.assertEqual(
            json.loads(response.content.decode('utf-8')),
            {
                'settings': {
                    'server': settings.CURRENT_INSTANCE_HOST,
                    'server_mode': settings.INSTANCE_IS_SLAVE and 'local' or 'saas',
                    'api_path': 'api',
                    'download_server': settings.CURRENT_INSTANCE_URL,
                    'version': 12345,
                    'need_app_update': True,
                    'client_id': settings.CLIENT_NAME,
                    'url_message_broker': settings.MESSAGE_BROKER_URL,
                    'port_message_broker': settings.MESSAGE_BROKER_PORT,
                    'default_theme_id': default_theme_pk,
                    'app_update': settings.LAST_IPA_VERSION_ITMS_URL,
                }
            }
        )
