# Path: web/carontepass/access/models.py
# class Device(models.Model):
#     __tablename__ = 'cp_device'
#     
#     NFC = 'nfc'
#     MAC = 'mac'
#     TAG = 'tag'
#     DEVICE_CHOICES = (
#         (NFC, 'NFC'),
#         (MAC, 'MAC'),
#         (TAG, 'TAG'),
#     )
# 
#     user = models.ForeignKey(User)
#     kind = models.CharField(max_length=3,
#                                       choices=DEVICE_CHOICES,
#                                       default=NFC,
#                                       blank=False,
#                                       )
#     code = models.CharField(max_length=64, blank=False)
#     
#     def __str__(self):
#         return 'Device {}:{} - {}'.format(self.user, self.kind, self.code)
#         
#     @staticmethod   
#     def check_exists_device(code_id):
#         #If there is no device code creates a new one.
#         #With this you have saved the new devices and then assign them to your user.
#         
#         if not Device.objects.filter(code=code_id):
#             caronte = User.objects.filter(username="caronte").first()
#             device_create = Device.objects.create(user=caronte, kind='tag', code=code_id)
# 
# class Log(models.Model):
#     __tablename__ = 'cp_log'
# 
#     user = models.ForeignKey(User)
#     ts_input = models.DateTimeField()
#     ts_output = models.DateTimeField()
#     user_in = models.BooleanField(default=False)
#     
#     def __str__(self):
#         return 'Log {}: {} - {}'.format(self.user, self.ts_input, self.ts_output)
#     
#    
#     @staticmethod   
#     def checkentryLog(Device):
# 
#         def domoticz_armed(armed='On'):
#             # Domoticz armed Security
#             http = urllib3.PoolManager()
#             url = 'http://'+DOMOTICZ_LOCALIP+'/json.htm?type=command&param=switchlight&idx='+DOMOTICZ_IDX+'&switchcmd='
#             headers = urllib3.util.make_headers(basic_auth=DOMOTICZ_USUER+':'+DOMOTICZ_PASS)
#             r = http.request('GET', url+armed, headers=headers)
#  
#         date = datetime.datetime.now()
# 
#         log_obj = Log.objects.filter(user=Device.user).last()
#         
#         log_user_in_initial = len(Log.objects.filter(user_in=True).all())
# 
#         if not log_obj:
# 
#             log_create = Log.objects.create(user=Device.user, ts_input=date, ts_output=date, user_in=True)
#             send_log_msg(True, str(Device.user.username))
#             
#         elif(log_obj.user_in == True):
#                     
#             log_obj.ts_output = datetime.datetime.now()
#             log_obj.user_in = False
#             log_obj.save()
#             send_log_msg(False, str(Device.user.username))
# 
#         else:
#             log_create = Log.objects.create(user=Device.user, ts_input=date, ts_output=date, user_in=True)    
#             send_log_msg(True, str(Device.user.username))
#      
#         log_user_in_end = len(Log.objects.filter(user_in=True).all())
#         
#         
#         if(log_user_in_initial == 0 and log_user_in_end == 1):
#             send_group_msg(True, str(Device.user.username))
#             # Site domoticz state On
#             domoticz_armed('On')
#             
#         elif(log_user_in_initial == 1 and log_user_in_end == 0):
#             send_group_msg(False, str(Device.user.username))
#             # Site domoticz state Off
#             domoticz_armed('Off')
#            
#             
#     @staticmethod   
#     def listUsersInside():
#         
#         users = Log.objects.filter(user_in=True).all()
#         
#         if users:
#             users_in_msg = 'People registered here are: {}'.format(
#             ', '.join([str(users[i].user.username) for i in range(len(users))])
#              )
#         else:
#              users_in_msg = 'Nobody inside'
#                 
#         
#         return users_in_msg
# 
# 
#     @staticmethod    
#     def listUsersCount():
# 
#         return Log.objects.filter(user_in=True).count()
# 
# Path: web/carontepass/access/serializers.py
# class DeviceResultSerializer(serializers.ModelSerializer):
#     
#     result = serializers.SerializerMethodField('is_auth_user')
#     
#     def is_auth_user(self, Device):
#         
#         #Check if the user has monthly payments
#         month_actual = datetime.datetime.now().month
#         
#         if Payment.objects.filter(user=Device.user, month=month_actual): 
#             if  Payment.objects.filter(user=Device.user, month=month_actual)[0].amount >= VALUE_PAYMENT_TRUE:
#                 
#                 Log.checkentryLog(Device)
#                 Message.message_detect_tag(Device)
#                 return True;
#         
#         
#         #Grace period for the first day of the month
#         if not Device.kind == "tag":
#             #The tags that have no assigned user are exempt from the days of courtesy.
#             day_actual = datetime.datetime.now().day
#             
#             if datetime.datetime.now().day <= MAX_GRANTED_DAYS:
#                 
#                 Log.checkentryLog(Device)
#                 Message.message_detect_tag(Device)
#                 
#                 return True;
#                 
#     class Meta:
#             model = Device
#             fields = ('id', 'user', 'kind', 'code', 'result')


from django.shortcuts import render
from rest_framework import generics
from .models import Device, Log
from .serializers import DeviceResultSerializer
from django.contrib.auth.models import User
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from graphos.renderers import flot, gchart
from graphos.sources.simple import SimpleDataSource
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.shortcuts import render




# Create your views here.

class DeviceIDList(generics.ListAPIView):

    serializer_class = DeviceResultSerializer

    def get_queryset(self, **kwargs):

        code_id = self.kwargs['code']
        
        Device.check_exists_device(code_id)
        

# Path: web/carontepass/access/models.py
# class Device(models.Model):
#     __tablename__ = 'cp_device'
#     
#     NFC = 'nfc'
#     MAC = 'mac'
#     TAG = 'tag'
#     DEVICE_CHOICES = (
#         (NFC, 'NFC'),
#         (MAC, 'MAC'),
#         (TAG, 'TAG'),
#     )
# 
#     user = models.ForeignKey(User)
#     kind = models.CharField(max_length=3,
#                                       choices=DEVICE_CHOICES,
#                                       default=NFC,
#                                       blank=False,
#                                       )
#     code = models.CharField(max_length=64, blank=False)
#     
#     def __str__(self):
#         return 'Device {}:{} - {}'.format(self.user, self.kind, self.code)
#         
#     @staticmethod   
#     def check_exists_device(code_id):
#         #If there is no device code creates a new one.
#         #With this you have saved the new devices and then assign them to your user.
#         
#         if not Device.objects.filter(code=code_id):
#             caronte = User.objects.filter(username="caronte").first()
#             device_create = Device.objects.create(user=caronte, kind='tag', code=code_id)
# 
# class Log(models.Model):
#     __tablename__ = 'cp_log'
# 
#     user = models.ForeignKey(User)
#     ts_input = models.DateTimeField()
#     ts_output = models.DateTimeField()
#     user_in = models.BooleanField(default=False)
#     
#     def __str__(self):
#         return 'Log {}: {} - {}'.format(self.user, self.ts_input, self.ts_output)
#     
#    
#     @staticmethod   
#     def checkentryLog(Device):
# 
#         def domoticz_armed(armed='On'):
#             # Domoticz armed Security
#             http = urllib3.PoolManager()
#             url = 'http://'+DOMOTICZ_LOCALIP+'/json.htm?type=command&param=switchlight&idx='+DOMOTICZ_IDX+'&switchcmd='
#             headers = urllib3.util.make_headers(basic_auth=DOMOTICZ_USUER+':'+DOMOTICZ_PASS)
#             r = http.request('GET', url+armed, headers=headers)
#  
#         date = datetime.datetime.now()
# 
#         log_obj = Log.objects.filter(user=Device.user).last()
#         
#         log_user_in_initial = len(Log.objects.filter(user_in=True).all())
# 
#         if not log_obj:
# 
#             log_create = Log.objects.create(user=Device.user, ts_input=date, ts_output=date, user_in=True)
#             send_log_msg(True, str(Device.user.username))
#             
#         elif(log_obj.user_in == True):
#                     
#             log_obj.ts_output = datetime.datetime.now()
#             log_obj.user_in = False
#             log_obj.save()
#             send_log_msg(False, str(Device.user.username))
# 
#         else:
#             log_create = Log.objects.create(user=Device.user, ts_input=date, ts_output=date, user_in=True)    
#             send_log_msg(True, str(Device.user.username))
#      
#         log_user_in_end = len(Log.objects.filter(user_in=True).all())
#         
#         
#         if(log_user_in_initial == 0 and log_user_in_end == 1):
#             send_group_msg(True, str(Device.user.username))
#             # Site domoticz state On
#             domoticz_armed('On')
#             
#         elif(log_user_in_initial == 1 and log_user_in_end == 0):
#             send_group_msg(False, str(Device.user.username))
#             # Site domoticz state Off
#             domoticz_armed('Off')
#            
#             
#     @staticmethod   
#     def listUsersInside():
#         
#         users = Log.objects.filter(user_in=True).all()
#         
#         if users:
#             users_in_msg = 'People registered here are: {}'.format(
#             ', '.join([str(users[i].user.username) for i in range(len(users))])
#              )
#         else:
#              users_in_msg = 'Nobody inside'
#                 
#         
#         return users_in_msg
# 
# 
#     @staticmethod    
#     def listUsersCount():
# 
#         return Log.objects.filter(user_in=True).count()
# 
# Path: web/carontepass/access/serializers.py
# class DeviceResultSerializer(serializers.ModelSerializer):
#     
#     result = serializers.SerializerMethodField('is_auth_user')
#     
#     def is_auth_user(self, Device):
#         
#         #Check if the user has monthly payments
#         month_actual = datetime.datetime.now().month
#         
#         if Payment.objects.filter(user=Device.user, month=month_actual): 
#             if  Payment.objects.filter(user=Device.user, month=month_actual)[0].amount >= VALUE_PAYMENT_TRUE:
#                 
#                 Log.checkentryLog(Device)
#                 Message.message_detect_tag(Device)
#                 return True;
#         
#         
#         #Grace period for the first day of the month
#         if not Device.kind == "tag":
#             #The tags that have no assigned user are exempt from the days of courtesy.
#             day_actual = datetime.datetime.now().day
#             
#             if datetime.datetime.now().day <= MAX_GRANTED_DAYS:
#                 
#                 Log.checkentryLog(Device)
#                 Message.message_detect_tag(Device)
#                 
#                 return True;
#                 
#     class Meta:
#             model = Device
#             fields = ('id', 'user', 'kind', 'code', 'result')


# Path: web/carontepass/access/views.py
from django.shortcuts import render
from rest_framework import generics
from .models import Device, Log
from .serializers import DeviceResultSerializer
from django.contrib.auth.models import User
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from graphos.renderers import flot, gchart
from graphos.sources.simple import SimpleDataSource
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.shortcuts import render





# Create your views here.

class DeviceIDList(generics.ListAPIView):

    serializer_class = DeviceResultSerializer

    def get_queryset(self, **kwargs):

        code_id = self.kwargs['code']
        
        Device.check_exists_device(code_id)
        

        return Device.objects.filter(code=code_id)