from django.shortcuts import render,redirect,get_object_or_404
from django.contrib import messages
from visitors_app.models import gate_pass_template
from visitors_app.context_processors import my_constants
from visitors_app.views import date_time
from django.utils.safestring import mark_safe
from django.db import connection
from django.http import JsonResponse
from django.template import Template, Context
import re
from django.template import engines
from visitors_app.check_subscription import check_subscription

@check_subscription
def admin_gate_pass(request):
    username = request.session.get('admin')
    if not username:
        return redirect('admin')

    return render(request, 'dashboard/admin_dashboard/admin_gate_pass/admin_gate_pass.html',{'function_name': 'Admin','username':username})

@check_subscription
def admin_gate_pass_template_ajax_page_ajax(request):
    constants = my_constants(request)
    username = request.session.get('admin')
    if not username:
        return redirect('admin')
    database_name = constants['database_name']
    start = request.POST.get('start', 0)
    length = request.POST.get('length', 10)
    search_value = request.POST.get('search[value]', '')
    search = ''
    if search_value != '':
        # search = f'WHERE visitors.first_name LIKE "%{search_value}%" or employees.first_name LIKE "%{search_value}%" or appointment.id LIKE "%{search_value}%" or appointment.date LIKE "%{search_value}%" or appointment.time LIKE "%{search_value}%" or appointment.purpose LIKE "%{search_value}%"'
        search = f'AND ( gate_pass_name LIKE "%{search_value}%" )'
    # First SQL query to get the count of appointments

    sql_query = f"""
            SELECT COUNT(*) AS gate_pass_template_count
            FROM {database_name}.gate_pass_template
            where 1=1 {search};
    """
    with connection.cursor() as cursor:
        cursor.execute(sql_query)
        database_all_data = cursor.fetchall()

    # Check if database_all_data is not empty before accessing its elements
    if database_all_data:
        recordsTotal = database_all_data[0][0]
    else:
        recordsTotal = 0

    # Second SQL query to get detailed appointment data
    sql_query = f"""
        select {database_name}.gate_pass_template.*
        from  {database_name}.gate_pass_template
        where 1=1 {search}
    	ORDER BY
    		gate_pass_template.id DESC 
        LIMIT {length} OFFSET {start};
    """
    # Execute the second SQL query
    with connection.cursor() as cursor:
        cursor.execute(sql_query)
        database_all_data = cursor.fetchall()
        columns = [col[0] for col in cursor.description]
        all_coupon_dtl = [dict(zip(columns, row)) for row in database_all_data]
    return JsonResponse({"recordsTotal": recordsTotal, "recordsFiltered": recordsTotal, 'data': all_coupon_dtl})

@check_subscription
def admin_gate_pass_template_edit(request, id):
    constants = my_constants(request)
    username = request.session.get('admin')
    if not username:
        return redirect('admin')
    user_data = constants.get('admin_data', {})
    all_gate_pass_template = get_object_or_404(gate_pass_template, id=id)
    if request.method == "POST":
        all_gate_pass_template.gate_pass_name = request.POST['gate_pass_name']
        all_gate_pass_template.gate_pass_template = request.POST['gate_pass_template']
        all_gate_pass_template.created_at = date_time()
        all_gate_pass_template.save()
        messages.success(request, "gate pass templates successfully Update.", extra_tags="success")
        return redirect('admin_gate_pass')
    return render(request, 'dashboard/admin_dashboard/admin_gate_pass/admin_gate_pass_edit.html',{'all_gate_pass_template':all_gate_pass_template,'function_name': 'Admin'})

def admin_gate_pass_template_view(request, id):
    constants = my_constants(request)

    template_obj = get_object_or_404(gate_pass_template, id=id)

    django_engine = engines['django']
    template_string = template_obj.gate_pass_template

    if '{% load static %}' not in template_string:
        template_string = "{% load static %}\n" + template_string

    context = {
        'formatted_gate_pass_number': 'VMS1',
        'check_in_time': '',
        'check_out_time': '',
        'visitors_type': 'Demo',
        'visitors_name': 'Dhruv Parikh',
        'visitors_image': constants.get('DEFAULT_IMAGE', ''),
        'visitors_address': 'Ahmedabad',
        'visitors_mobile': '7600524348',
        'employee_name': 'Demo Employee',
        'company_name': 'Demo Company',
        'department_name': 'IT',
        'location_name': 'Main Office',
        'location_address': 'Ahmedabad',
        'appointment': 'Demo Appointment',
        'GET_PASS_IMAGE': constants.get('GET_PASS_IMAGE', ''),
        'device':'abc',
        'visitor_company_name': 'ABC'
    }

    rendered_html = django_engine.from_string(
        template_string
    ).render(context)

    return JsonResponse({
        'status': True,
        'template_name': template_obj.gate_pass_name,
        'html': rendered_html
    })
