# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import os
from urllib2 import urlopen

from django.http import StreamingHttpResponse
from django.shortcuts import render_to_response, get_object_or_404
from django.views.generic.detail import DetailView
from django.views.generic.edit import UpdateView
from django.conf import settings
from django.contrib.messages.views import SuccessMessageMixin
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator

from coin.members.models import Member
from coin.vpn.models import VPNConfiguration


class VPNView(SuccessMessageMixin, UpdateView):
    model = VPNConfiguration
    fields = ['ipv4_endpoint', 'ipv6_endpoint', 'comment']
    success_message = "Configuration enregistrée avec succès !"

    @method_decorator(login_required)
    def dispatch(self, *args, **kwargs):
        return super(VPNView, self).dispatch(*args, **kwargs)

    def get_object(self):
        if self.request.user.is_superuser:
            return get_object_or_404(VPNConfiguration, pk=self.kwargs.get("id"))
        # For normal users, ensure the VPN belongs to them.
        return get_object_or_404(VPNConfiguration, pk=self.kwargs.get("id"),
                                 offersubscription__member=self.request.user)


class VPNGeneratePasswordView(VPNView):
    """This generates a random password, saves it in hashed form, and returns
    it to the user in cleartext.
    """

    def get_context_data(self, **kwargs):
        context = super(VPNGeneratePasswordView, self).get_context_data(**kwargs)
        # Generate a new random password and save it
        password = Member.objects.make_random_password()
        self.object.password = password
        # This will hash the password automatically
        self.object.full_clean()
        self.object.save()
        context['password'] = password
        return context


def get_graph(request, vpn_id, period="daily"):
    """ This get the graph for the associated vpn_id and time period
    """
    if request.user.is_superuser:
        vpn = get_object_or_404(VPNConfiguration, pk=vpn_id)
    else:
        # For normal users, ensure the VPN belongs to them
        vpn = get_object_or_404(VPNConfiguration, pk=vpn_id,
                                offersubscription__member=request.user)

    time_periods = { 'hourly': '-1hour', 'daily': '-24hours', 'weekly': '-8days', 'monthly': '-32days', 'yearly': '-13months', }
    if period not in time_periods:
        period = 'daily'

    graph_url = os.path.join(settings.GRAPHITE_SERVER,
                "render/?width=586&height=308&from=%(period)s&" \
                "target=alias%%28scaleToSeconds%%28vpn1.%(login)s.downrxbytes%%2C1%%29%%2C%%20%%22Download%%22%%29&" \
                "target=alias%%28scaleToSeconds%%28vpn1.%(login)s.uptxbytes%%2C1%%29%%2C%%20%%22Upload%%22%%29&" \
                "title=VPN%%20Usage%%20%(login)s" % \
                    { 'period': time_periods[period], 'login': vpn.login })
    return StreamingHttpResponse(urlopen(graph_url), content_type="image/png")
