# Path: app/models/startup.py
# class Startup(models.Model):
#     class Meta:
#         app_label = 'app'
# 
#     name = models.CharField(max_length=255,db_index=True,unique=True)
#     url = models.URLField(max_length=255,unique=True,blank=True,null=True)
# 
#     def __unicode__(self):
#         return self.name
# 
#     @staticmethod
#     def get_from_mailbox(mailbox):
#         if mailbox.startup_id: return mailbox.startup
# 
#         obj, created = Startup.objects.get_or_create(name=mailbox.username.capitalize())
#         return obj
# 
# Path: app/models/startuppermission.py
# class StartupPermission(models.Model):
#     """
#     If the user is on allow default mode -> it says the user cannot see this startup
#     If the user is on deny default mode -> it says the user can see this startup
#     """
#     class Meta:
#         unique_together = (("user", "startup"),)
# 
#     user = models.ForeignKey(settings.AUTH_USER_MODEL)
#     startup = models.ForeignKey('Startup')
# 
#     @staticmethod
#     def has_user_permission(user, startup):
#         cache_key = u"has_user_permission|{0}|{1}".format(user.id,startup.id)
#         if cache.get(cache_key): return cache.get(cache_key)
# 
#         from app.models.userprofile import UserProfile
#         userprofile = UserProfile.objects.get_or_create(user=user)[0]
# 
#         if userprofile.permission_mode == UserProfile.PERMISSION_ALLOW_DEFAULT:
#             has_user_permission = (not StartupPermission.objects.filter(user=user, startup=startup).exists())
#         else:
#             has_user_permission = (StartupPermission.objects.filter(user=user, startup=startup).exists())
# 
#         cache.set(cache_key, has_user_permission, 10) # 10 secs cache
#         return has_user_permission
# 
#     @staticmethod
#     def startups_allowed(user):
#         from app.models.userprofile import UserProfile
#         userprofile = UserProfile.objects.get_or_create(user=user)[0]
# 
#         startup_permission_ids = StartupPermission.objects.filter(user=user).values_list('startup_id', flat=True)
# 
#         if userprofile.permission_mode == UserProfile.PERMISSION_ALLOW_DEFAULT:
#             return Startup.objects.exclude(id__in=startup_permission_ids)
#         else:
#             return Startup.objects.filter(id__in=startup_permission_ids)
# 
#     @staticmethod
#     def users_allowed(startup):
#         cache_key = u"users_allowed|{0}".format(startup.id)
#         if cache.get(cache_key): return cache.get(cache_key)
# 
#         users_allowed = []
#         for u in get_user_model().objects.filter(is_active=True):
#             if StartupPermission.has_user_permission(u, startup):
#                 users_allowed.append(u)
# 
#         cache.set(cache_key, users_allowed, 30)  # 30 secs cache
#         return users_allowed
# 
# Path: app/models/userprofile.py
# class UserProfile(models.Model):
#     class Meta:
#         app_label = 'app'
# 
#     PERMISSION_ALLOW_DEFAULT = 0
#     PERMISSION_DENY_DEFAULT = 1
#     PERMISSION_CHOICES = (
#         (PERMISSION_ALLOW_DEFAULT, "Allow default"),
#         (PERMISSION_DENY_DEFAULT, "Deny default")
#     )
#     user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
# 
#     permission_mode = models.IntegerField(choices=PERMISSION_CHOICES,default=PERMISSION_ALLOW_DEFAULT)
#     relay_email = models.BooleanField(default=True)
# 
# Path: app/utils.py
# def staff_required(view):
#     def f(request, *args, **kwargs):
#         if not request.user.is_staff:
#             return HttpResponseRedirect("/")
#         return view(request, *args, **kwargs)
# 
#     return f


import shortuuid
from django import forms
from django.contrib.auth import get_user_model
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.http import Http404
from django.http import HttpResponseRedirect
from django.shortcuts import render, get_object_or_404
from django.urls import reverse
from rest_framework import serializers
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from app.models import StartupPermission, UserProfile, Startup
from app.utils import staff_required
def startup_list(request):
    startups = Startup.objects.all().order_by('name')

    # TODO : This might not be efficient enough
    user_permissions = {}
    user_list = User.objects.filter(is_active=True)
    for startup in startups:
        permission_map = []
        for user in user_list:
            permission_map.append((user,StartupPermission.has_user_permission(user, startup)))
        user_permissions[startup.id] = permission_map

    return render(request, "admin/admin_startup_list.html", {"startups": startups,
                                                             "user_permissions": user_permissions,
                                                             "cur_admin_page": "startup"})


class StartupPermissionSerializer(serializers.Serializer):
    user_id = serializers.IntegerField()
    has_permission = serializers.BooleanField()

    def validate_user_id(self, value):
        if not User.objects.filter(id=value).exists():
            raise serializers.ValidationError("User doesn't exist")
        return value

@login_required
@staff_required
@api_view(['POST'])
def startup_permission(request, startup_id):

# Path: app/models/startup.py
# class Startup(models.Model):
#     class Meta:
#         app_label = 'app'
# 
#     name = models.CharField(max_length=255,db_index=True,unique=True)
#     url = models.URLField(max_length=255,unique=True,blank=True,null=True)
# 
#     def __unicode__(self):
#         return self.name
# 
#     @staticmethod
#     def get_from_mailbox(mailbox):
#         if mailbox.startup_id: return mailbox.startup
# 
#         obj, created = Startup.objects.get_or_create(name=mailbox.username.capitalize())
#         return obj
# 
# Path: app/models/startuppermission.py
# class StartupPermission(models.Model):
#     """
#     If the user is on allow default mode -> it says the user cannot see this startup
#     If the user is on deny default mode -> it says the user can see this startup
#     """
#     class Meta:
#         unique_together = (("user", "startup"),)
# 
#     user = models.ForeignKey(settings.AUTH_USER_MODEL)
#     startup = models.ForeignKey('Startup')
# 
#     @staticmethod
#     def has_user_permission(user, startup):
#         cache_key = u"has_user_permission|{0}|{1}".format(user.id,startup.id)
#         if cache.get(cache_key): return cache.get(cache_key)
# 
#         from app.models.userprofile import UserProfile
#         userprofile = UserProfile.objects.get_or_create(user=user)[0]
# 
#         if userprofile.permission_mode == UserProfile.PERMISSION_ALLOW_DEFAULT:
#             has_user_permission = (not StartupPermission.objects.filter(user=user, startup=startup).exists())
#         else:
#             has_user_permission = (StartupPermission.objects.filter(user=user, startup=startup).exists())
# 
#         cache.set(cache_key, has_user_permission, 10) # 10 secs cache
#         return has_user_permission
# 
#     @staticmethod
#     def startups_allowed(user):
#         from app.models.userprofile import UserProfile
#         userprofile = UserProfile.objects.get_or_create(user=user)[0]
# 
#         startup_permission_ids = StartupPermission.objects.filter(user=user).values_list('startup_id', flat=True)
# 
#         if userprofile.permission_mode == UserProfile.PERMISSION_ALLOW_DEFAULT:
#             return Startup.objects.exclude(id__in=startup_permission_ids)
#         else:
#             return Startup.objects.filter(id__in=startup_permission_ids)
# 
#     @staticmethod
#     def users_allowed(startup):
#         cache_key = u"users_allowed|{0}".format(startup.id)
#         if cache.get(cache_key): return cache.get(cache_key)
# 
#         users_allowed = []
#         for u in get_user_model().objects.filter(is_active=True):
#             if StartupPermission.has_user_permission(u, startup):
#                 users_allowed.append(u)
# 
#         cache.set(cache_key, users_allowed, 30)  # 30 secs cache
#         return users_allowed
# 
# Path: app/models/userprofile.py
# class UserProfile(models.Model):
#     class Meta:
#         app_label = 'app'
# 
#     PERMISSION_ALLOW_DEFAULT = 0
#     PERMISSION_DENY_DEFAULT = 1
#     PERMISSION_CHOICES = (
#         (PERMISSION_ALLOW_DEFAULT, "Allow default"),
#         (PERMISSION_DENY_DEFAULT, "Deny default")
#     )
#     user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
# 
#     permission_mode = models.IntegerField(choices=PERMISSION_CHOICES,default=PERMISSION_ALLOW_DEFAULT)
#     relay_email = models.BooleanField(default=True)
# 
# Path: app/utils.py
# def staff_required(view):
#     def f(request, *args, **kwargs):
#         if not request.user.is_staff:
#             return HttpResponseRedirect("/")
#         return view(request, *args, **kwargs)
# 
#     return f


# Path: app/views_admin.py
import shortuuid
from django import forms
from django.contrib.auth import get_user_model
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.http import Http404
from django.http import HttpResponseRedirect
from django.shortcuts import render, get_object_or_404
from django.urls import reverse
from rest_framework import serializers
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from app.models import StartupPermission, UserProfile, Startup
from app.utils import staff_required

def startup_list(request):
    startups = Startup.objects.all().order_by('name')

    # TODO : This might not be efficient enough
    user_permissions = {}
    user_list = User.objects.filter(is_active=True)
    for startup in startups:
        permission_map = []
        for user in user_list:
            permission_map.append((user,StartupPermission.has_user_permission(user, startup)))
        user_permissions[startup.id] = permission_map

    return render(request, "admin/admin_startup_list.html", {"startups": startups,
                                                             "user_permissions": user_permissions,
                                                             "cur_admin_page": "startup"})


class StartupPermissionSerializer(serializers.Serializer):
    user_id = serializers.IntegerField()
    has_permission = serializers.BooleanField()

    def validate_user_id(self, value):
        if not User.objects.filter(id=value).exists():
            raise serializers.ValidationError("User doesn't exist")
        return value

@login_required
@staff_required
@api_view(['POST'])
def startup_permission(request, startup_id):

    startup = get_object_or_404(Startup, id=startup_id)