import datetime

from django.contrib import messages
from django.db.models import Count
from django.db.models.functions import TruncDay
from django.http import JsonResponse
from django.utils.timezone import make_aware
from django.utils.translation import gettext_lazy as _
from django.views.generic import FormView, View

from passerelle.base.models import SkipJob
from passerelle.utils.jsonresponse import APIError
from passerelle.views import GenericConnectorMixin

from .forms import SmsTestSendForm
from .models import SMSLog


class SmsTestSendView(GenericConnectorMixin, FormView):
    template_name = 'passerelle/manage/messages_service_test_send.html'

    def get_form_class(self):
        return SmsTestSendForm

    def get_object(self):
        return self.model.objects.get(slug=self.kwargs['slug'])

    def get_success_url(self):
        connector = self.get_object()
        return connector.get_absolute_url()

    def form_valid(self, form):
        number = form.cleaned_data['number']
        sender = form.cleaned_data['sender']
        message = form.cleaned_data['message']
        connector = self.get_object()
        try:
            number = connector.clean_numbers([number])[0]
            number = connector.authorize_numbers([number])[0][0]
            connector.send_msg(text=message, sender=sender, destinations=[number], stop=False)
        except (APIError, SkipJob) as exc:
            messages.error(self.request, _('Sending SMS fails: %s' % exc))
        else:
            messages.success(self.request, _('An SMS was just sent'))
        return super().form_valid(form)


class SmsStatisticsView(View):
    def get(self, request, *args, **kwargs):
        if 'time_interval' in request.GET and request.GET['time_interval'] != 'day':
            return JsonResponse({'err': 1, 'err_desc': 'unsupported time interval'})

        logs = SMSLog.objects.filter(appname=kwargs['connector'], slug=kwargs['slug'])
        if 'start' in request.GET:
            start = make_aware(datetime.datetime.strptime(request.GET['start'], '%Y-%m-%d'))
            logs = logs.filter(timestamp__gte=start)
        if 'end' in request.GET:
            end = make_aware(datetime.datetime.strptime(request.GET['end'], '%Y-%m-%d'))
            logs = logs.filter(timestamp__lte=end)

        logs = logs.annotate(day=TruncDay('timestamp'))
        logs = logs.values('day').annotate(total=Count('id')).order_by('day')

        x_labels, data = [], []
        for log in logs:
            x_labels.append(log['day'].strftime('%Y-%m-%d'))
            data.append(log['total'])

        return JsonResponse(
            {
                'data': {
                    'x_labels': x_labels,
                    'series': [
                        {
                            'label': _('SMS Count'),
                            'data': data,
                        }
                    ],
                }
            }
        )
