import json
import mimetypes
import os
import socket
import sqlite3
import cv2

from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, Http404, JsonResponse
from django.shortcuts import render
from django.utils._os import safe_join
from django.views.decorators.cache import never_cache
from django.core.cache import cache

from .forms import *
from admin_base.functions import *
from cms.functions import *

def demo(request):
    
    content = database.read_database(db_path, "demo")
    
    context = {
    "content": content
    }    
    return render(request, 'demo.html', context)

@login_required(login_url='/admin/login/')
def cms_page(request, file_directory_attr, db_table_attr, page_name="Admin"):
    """
    Handles dynamic CMS requests and pages for the CMS app.

    Args:
        request (HttpRequest): The current HTTP request.
        file_directory_attr (str): The directory attribute for the file.
        db_table_attr (str): The database table attribute.

    Returns:
        HttpResponse: The rendered CMS template with form and context.
    """
    
    hostname = socket.gethostname()
    IPAddr = socket.gethostbyname(hostname)

    # Load dynamic file directory with content_index
    file_directory_json_path = Path(__file__).parent / f"content_index/{get_language()}/{file_directory_attr}"
    with open(file_directory_json_path, encoding="utf8") as file_directory_json:
        data = json.load(file_directory_json)

    form = base_form(request.POST or None, file_directory_form=file_directory_attr, db_table_form=db_table_attr)

    parent_media_path = os.path.join(settings.WEBSITE_MEDIA_ROOT, db_table_attr)
    
    if request.method == 'POST' and form.is_valid():
        # Proccess form data and flatten it out
        fields_flat = []
        
        db_path = f"cms/storage/content_{get_language()}.sqlite3"
        
        db_values = database.read_database(db_path, db_table_attr)
        
        #print(db_values)
      
        for form_fields in data: 
            page = form_fields
            
            for unprocessed_field in data[page]:
        
                try:
                    unprocessed_field["title"]
                    
                    if unprocessed_field['type'] == 'image':
                        uploaded_img = request.FILES.get(unprocessed_field['form_name'])
                                                
                        if uploaded_img is None:
                            pass
                        
                        else:
                            fields_flat.append(unprocessed_field)
                    
                    else:
                        if request.POST.get(unprocessed_field['form_name']) != db_values[unprocessed_field['form_name']]:
                            fields_flat.append(unprocessed_field)
                            
                        else:
                            pass

                except:
                    for post_fields in unprocessed_field:
                        for fields_modified in unprocessed_field[post_fields]:
                            
                            if fields_modified['type'] == 'image':
                                uploaded_img = request.FILES.get(fields_modified['form_name'])
                                                
                                if uploaded_img is None:
                                    pass
                                
                                else:
                                    fields_flat.append(unprocessed_field)
                                
                            else:
                                if request.POST.get(fields_modified['form_name']) != db_values[fields_modified['form_name']]:
                                    fields_flat.append(fields_modified)
                                    
                                else:
                                    pass
        
        print(fields_modified)
                          
        # Loop through fields and handle accordingly
        for field in fields_flat:
            field_type = field.get('type')
            field_name = field.get('form_name')
            
            # print("Field Name ", field_name)
            # print("Field Data ", field)
            # print("Field inner text ", request.POST.get(field['form_name']))
            # print("DB attr ", db_table_attr)
            # print('DB Path ', db_path)
            # print("Field initial Text ", database.read(db_path, db_table_attr, field_name))
            # print("")

            if field_type == "image":
                uploaded_image = request.FILES.get(field_name)
                
                if uploaded_image:
                    update_image(parent_media_path, db_path, uploaded_image, field_name, db_table_attr)
                    pass
                      
            else:
                new_value = request.POST.get(field_name)
                update_text_field(db_path, db_table_attr, field_name, new_value)
                

    # Log admin access
    log(f"Admin access granted from IP: {IPAddr}, with Name: {hostname}")

    context = {
        'form': form,
        "data": data,
        "title": page_name,
        'table_attr': db_table_attr
    }

    return render(request, 'cms_main.html', context)

def upload_file(request):
    if request.method == 'POST':
        # Check if the request contains files
        if request.FILES:
            # If there is a file, we assume it's being uploaded correctly
            print("Success")
            return JsonResponse({'status': 'success', 'message': 'File uploaded successfully'}, status=200)
        else:
            print("Error 1")
            return JsonResponse({'status': 'error', 'message': 'No file uploaded'}, status=400)
    else:
        print("Error 2")
        return JsonResponse({'status': 'error', 'message': 'Invalid request method'}, status=405)


def serve_media(request, app_name, path):
    """
    Serve media files from app-specific media directories.
    """
    # Define the media root for each app
    media_root = os.path.join(settings.BASE_DIR, app_name, 'media')
    
    # Safely join the path to avoid directory traversal issues
    file_path = safe_join(media_root, path)

    if not os.path.exists(file_path):
        raise Http404('Media file not found')

    # Get the file mime type
    mime_type, _ = mimetypes.guess_type(file_path)
    
    # Open the file and return it as a response
    with open(file_path, 'rb') as f:
        return HttpResponse(f.read(), content_type=mime_type)