import random
import time
from django.db import connection
from django.contrib.auth.models import *

'''
 generate employee usernamex
'''

def getTodaysdate():
    return time.strftime("%Y-%m-%d")

def genEmpUsername():
    id = time.strftime("%y") + '%s' %str(random.randint(100, 999))
    return id

def genStudId():
    id = time.strftime("%Y") + '%s' %str(random.randint(1000, 9999))
    return id

def getRequest(request, name):
    if request.method=='GET':
        return request.GET.get(name)
    if request.method=='POST':
        return request.POST.get(name)

'''
pagination limit offset update
'''    

def upload_file(destination, f):
    with open(destination + f.name, 'wb+') as destination:
        for chunk in f.chunks():
            destination.write(chunk)

def prev_offset(of, lm):
    if of-lm<0:
        return of
    else:
        return of-lm

def next_offset(of, lm, size):
    if of+lm>size:
        return of
    else:
        return of+lm


'''
user access validattion script
'''
def hasAccess(user_id, model_table):
    user = User.objects.get(id=user_id)
    if user.is_superuser:
        return True
    else:
        cursor = connection.cursor()
        cursor.execute('''SELECT auth_group.* FROM auth_group, auth_user_groups WHERE 
        auth_group.id = auth_user_groups.group_id  AND 
        auth_user_groups.user_id=%s''', [user_id])
        user_groups = cursor.fetchall()
        for grp in user_groups:
            cursor.execute('''SELECT COUNT(*) FROM group_perms_view gpv
            WHERE gpv.model=%s AND gpv.group_id=%s''',[model_table, grp[0]])
            if cursor.fetchone()[0]>0:
                return True
        return False
