import uuid

from django.contrib import messages
from django.shortcuts import reverse
from django.utils.translation import gettext_lazy as _
from django.views.generic.base import RedirectView
from requests import RequestException

from .models import OVHSMSGateway


class RequestTokenView(RedirectView):
    def get_redirect_url(self, *args, **kwargs):
        connector = OVHSMSGateway.objects.get(slug=kwargs["slug"])

        request_id = uuid.uuid4()
        confirm_token_url = reverse('ovh-confirm-token', kwargs={'slug': connector.slug, 'uuid': request_id})
        data = {
            "accessRules": [
                {"method": "GET", "path": "/sms/%s/" % connector.account},
                {"method": "POST", "path": "/sms/%s/jobs/" % connector.account},
            ],
            "redirection": self.request.build_absolute_uri(confirm_token_url),
        }
        headers = {"X-Ovh-Application": connector.application_key}

        try:
            resp = connector.requests.post(
                'https://eu.api.ovh.com/1.0/auth/credential', json=data, headers=headers
            )
        except RequestException as e:
            messages.error(self.request, _('There has been an error requesting token: %s.') % e)
            return connector.get_absolute_url()
        try:
            result = resp.json()
        except ValueError:
            messages.error(self.request, _('There has been an error requesting token: bad JSON response.'))
            return connector.get_absolute_url()
        try:
            resp.raise_for_status()
        except RequestException:
            error_text = result.get('message', result)
            messages.error(self.request, _('There has been an error requesting token: %s.') % error_text)
            return connector.get_absolute_url()

        self.request.session['ovh-token-%s' % request_id] = result['consumerKey']
        return result['validationUrl']


class ConfirmTokenView(RedirectView):
    def get_redirect_url(self, *args, **kwargs):
        connector = OVHSMSGateway.objects.get(slug=kwargs["slug"])
        consumer_key = self.request.session.get('ovh-token-%s' % kwargs['uuid'])

        if consumer_key:
            connector.consumer_key = consumer_key
            connector.save()
            messages.success(self.request, _('Successfuly completed connector configuration.'))
        else:
            messages.warning(self.request, _('Could not complete connector configuration, please try again.'))

        return connector.get_absolute_url()
