"""This module contains the base test cases for the ``api`` app"""

import datetime
import json

from django.test import Client
from django.utils import timezone

from rest_framework.test import APITestCase
from oauth2_provider.models import AccessToken, Application

from mtp.apps.common.tests.test_cases import BaseMTPTestCase


class MTPAPITestCase(BaseMTPTestCase, APITestCase):
    """A test case based on ``BaseMTPTestCase`` and ``APITestCase``.

    Should be used in most cases.

    """

    def get_api_response(self, url, method, data):
        """Shortcut method to query the given url of the api

        Parameters
        ----------
        url: str
            The api url to query
        method: str, can be any http method
            The http method to use
        data: dict
            The data to send to the url, when using a "POST" method for example

        Returns
        -------
        tuple(int, dict):
            The response status code and the decoded response if applicable

        """

        response = getattr(self.client, method)(url, data)

        return response.status_code, json.loads(response.content.decode('utf-8'))


class MTPOAuthClientTestCaseMixin:
    """Mixin who provide an oauth client to test API endpoints"""

    @classmethod
    def setUpTestData(cls):
        """Create the ``oauth_client``"""

        super().setUpTestData()

        # Create a new OAuth2 Application
        cls.oauth_application = Application.objects.create(
            name="Test Application",
            user=cls.admin,
            client_type=Application.CLIENT_CONFIDENTIAL,
            authorization_grant_type=Application.GRANT_PASSWORD,
        )

        # Create our access token
        access_token = AccessToken.objects.create(
            token='1234567890',
            application=cls.oauth_application,
            expires=timezone.now() + datetime.timedelta(days=1),
            scope='read write')

        cls.oauth_client = Client(Authorization='Bearer %s' % access_token)
