# Path: RandoAmisSecours/models.py
# class Profile(models.Model):
#     class Meta:
#         app_label = 'RandoAmisSecours'
# 
#     user = models.OneToOneField(User)
#     friends = models.ManyToManyField('self', blank=True)
#     phone_number = models.CharField(max_length=30, blank=True, null=True)
#     provider = models.CharField(max_length=30, blank=True, null=True, choices=PROVIDERS)
#     provider_data = models.TextField(blank=True, null=True)
#     hash_id = models.CharField(unique=True, max_length=30, default=random_hash)
#     language = models.CharField(max_length=4, blank=True, null=True, choices=LANGUAGES)
#     timezone = models.CharField(max_length=40, choices=[(tz, tz) for tz in pytz.all_timezones], default='UTC')
# 
#     def clean(self):
#         if self.provider_data:
#             try:
#                 json.loads(self.provider_data)
#             except Exception:
#                 raise ValidationError({'provider_data': [ugettext('This should be JSON serialized')]})
# 
#         if self.timezone == 'UTC':
#             raise ValidationError({'timezone': [ugettext('UTC is not valid timezone')]})
# 
#     def __str__(self):
#         return "%s" % (self.user)
# 
# class FriendRequest(models.Model):
#     class Meta:
#         app_label = 'RandoAmisSecours'
# 
#     user = models.ForeignKey(User, related_name='+')
#     to = models.ForeignKey(User, related_name='+')
#     creation = models.DateTimeField(auto_now=True)
# 
#     def __str__(self):
#         return "%s => %s" % (self.user.get_full_name(), self.to.get_full_name())
# 
# Path: RandoAmisSecours/utils.py
# def send_localized_mail(user, subject, template_name, ctx):
#     with Localize(user.profile.language,
#                   user.profile.timezone):
#         send_mail_help(user, subject, template_name, ctx)


from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse
from django.db.models import Q
from django.http import Http404, HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.utils.translation import ugettext as _
from RandoAmisSecours.models import Profile, FriendRequest
from RandoAmisSecours.utils import send_localized_mail
    # Find the friend to request
    new_friend = get_object_or_404(Profile, user__pk=user_id)

    # Create the friend request
    friend_request = FriendRequest(user=request.user, to=new_friend.user)
    friend_request.save()

    # Alert the requester and the requested
    send_localized_mail(new_friend.user, _('[R.A.S.] Friend request'),
                        'RandoAmisSecours/friends/request_email.html',
                        {'from': friend_request.user.get_full_name(),
                         'to': friend_request.to.get_full_name(),
                         'accept': request.build_absolute_uri(reverse('friends.accept',
                                                                      args=[friend_request.pk])),
                         'refuse': request.build_absolute_uri(reverse('friends.refuse',
                                                                      args=[friend_request.pk]))})
    messages.success(request, _("Friend request sent to «%(name)s»") % ({'name': new_friend.user.get_full_name()}))

    return HttpResponseRedirect(reverse('friends.search'))


@login_required
def accept(request, request_id):
    friend_request = get_object_or_404(FriendRequest, pk=request_id, to=request.user)
    new_friend = get_object_or_404(Profile, user=friend_request.user)

    # Add the friend
    request.user.profile.friends.add(new_friend)
    friend_request.delete()


# Path: RandoAmisSecours/models.py
# class Profile(models.Model):
#     class Meta:
#         app_label = 'RandoAmisSecours'
# 
#     user = models.OneToOneField(User)
#     friends = models.ManyToManyField('self', blank=True)
#     phone_number = models.CharField(max_length=30, blank=True, null=True)
#     provider = models.CharField(max_length=30, blank=True, null=True, choices=PROVIDERS)
#     provider_data = models.TextField(blank=True, null=True)
#     hash_id = models.CharField(unique=True, max_length=30, default=random_hash)
#     language = models.CharField(max_length=4, blank=True, null=True, choices=LANGUAGES)
#     timezone = models.CharField(max_length=40, choices=[(tz, tz) for tz in pytz.all_timezones], default='UTC')
# 
#     def clean(self):
#         if self.provider_data:
#             try:
#                 json.loads(self.provider_data)
#             except Exception:
#                 raise ValidationError({'provider_data': [ugettext('This should be JSON serialized')]})
# 
#         if self.timezone == 'UTC':
#             raise ValidationError({'timezone': [ugettext('UTC is not valid timezone')]})
# 
#     def __str__(self):
#         return "%s" % (self.user)
# 
# class FriendRequest(models.Model):
#     class Meta:
#         app_label = 'RandoAmisSecours'
# 
#     user = models.ForeignKey(User, related_name='+')
#     to = models.ForeignKey(User, related_name='+')
#     creation = models.DateTimeField(auto_now=True)
# 
#     def __str__(self):
#         return "%s => %s" % (self.user.get_full_name(), self.to.get_full_name())
# 
# Path: RandoAmisSecours/utils.py
# def send_localized_mail(user, subject, template_name, ctx):
#     with Localize(user.profile.language,
#                   user.profile.timezone):
#         send_mail_help(user, subject, template_name, ctx)


# Path: RandoAmisSecours/views/friends.py
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse
from django.db.models import Q
from django.http import Http404, HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.utils.translation import ugettext as _
from RandoAmisSecours.models import Profile, FriendRequest
from RandoAmisSecours.utils import send_localized_mail

    # Find the friend to request
    new_friend = get_object_or_404(Profile, user__pk=user_id)

    # Create the friend request
    friend_request = FriendRequest(user=request.user, to=new_friend.user)
    friend_request.save()

    # Alert the requester and the requested
    send_localized_mail(new_friend.user, _('[R.A.S.] Friend request'),
                        'RandoAmisSecours/friends/request_email.html',
                        {'from': friend_request.user.get_full_name(),
                         'to': friend_request.to.get_full_name(),
                         'accept': request.build_absolute_uri(reverse('friends.accept',
                                                                      args=[friend_request.pk])),
                         'refuse': request.build_absolute_uri(reverse('friends.refuse',
                                                                      args=[friend_request.pk]))})
    messages.success(request, _("Friend request sent to «%(name)s»") % ({'name': new_friend.user.get_full_name()}))

    return HttpResponseRedirect(reverse('friends.search'))


@login_required
def accept(request, request_id):
    friend_request = get_object_or_404(FriendRequest, pk=request_id, to=request.user)
    new_friend = get_object_or_404(Profile, user=friend_request.user)

    # Add the friend
    request.user.profile.friends.add(new_friend)
    friend_request.delete()


    send_localized_mail(new_friend.user, _('[R.A.S.] Friend request accepted'),