# Import necessary modules and classes from Django and Python
from django import forms
from django.forms import ModelForm
import json
from pathlib import Path
from .models import *  # Import all models from the current app
from admin_base.functions import *  # Import all functions from the base module
import logging
from django.utils.translation import get_language
from django.conf import settings

logger = logging.getLogger(__name__)

# Define a function to dynamically create form fields based on field names and types
def create_form_fields(field_names, field_type, db_table):
    """
    Creates a dictionary of form fields based on the provided field names and types.

    Args:
        field_names (list): A list of field names.
        field_type (list): A list of field types corresponding to the field names.
        db_table (str): The name of the database table to read default values from.

    Returns:
        dict: A dictionary of form fields.
    """
    fields = {}
    
    # Iterate over the field names and types
    for name, field_type in zip(field_names, field_type):
        global db_path
        
        language = get_language()

        db_path = os.path.join(settings.BASE_DIR, f"cms/storage/content_{language}.sqlite3")
        
        # print(db_path, db_table, name)
        
        # Read the default value from the database
        default_value = database.read(db_path, db_table, name)
        
        # Create a form field based on the field type
        if field_type == "text":
            # Create a text input field with the default value
            fields[name] = forms.CharField(widget=forms.TextInput(attrs={'value': default_value[0][0]}))
            
        elif field_type == "textarea":
            # Create a textarea field with the default value
            fields[name] = forms.CharField(initial=default_value[0][0] ,widget=forms.Textarea(attrs={"rows": 5}))
            
        elif field_type == "password":
            # Create a password input field with the default value
            fields[name] = forms.CharField(widget=forms.PasswordInput(attrs={'value': default_value[0][0]}))
            
        elif field_type == "image":
            # Create an image upload field
            fields[name] = forms.ImageField()
            
        else:
            # Create a text input field with the default value (default case)
            fields[name] = forms.CharField(widget=forms.TextInput(attrs={'value': default_value[0][0]}))
    
    return fields

# Define a base form class that dynamically creates form fields
class base_form(ModelForm):
    """
    A base form class that dynamically creates form fields based on a JSON file.

    Args:
        file_directory_form (str): The directory of the JSON file containing form field definitions.
        db_table_form (str): The name of the database table to read default values from.
    """
    def __init__(self, *args, file_directory_form=None, db_table_form=None, **kwargs):
        super(base_form, self).__init__(*args, **kwargs)
    
        # Open the JSON file containing form field definitions
        file_directory = Path(__file__).parent / f"content_index/{get_language()}/{file_directory_form}"
        file_directory = open(file_directory, encoding="utf8")
        data = json.load(file_directory)
        
        # Extract field names and types from the JSON data
        field_names = []
        field_type = []

        for form_fields in data:
            page = form_fields
            
            for fields in data[f"{page}"]:
                try:
                    try:
                        fields["title"]
                        field_names.append(fields["form_name"])
                        field_type.append(fields["type"])
                        
                    except:
                        fields["expandable_field"]
                        
                except:
                    for post_fields in fields:
                        for fields in fields[post_fields]:
                            field_names.append(fields["form_name"])
                            field_type.append(fields["type"])
        
        # Dynamically create form fields
        form_fields = create_form_fields(field_names, field_type, db_table=f"{db_table_form}")
            
        # Add form fields to the form class
        for field_name, field in form_fields.items():
            if isinstance(field, forms.ImageField):
                # Make image fields optional
                self.fields[field_name] = field
                self.fields[field_name].required = False
            else:
                self.fields[field_name] = field
                
        # print(self.fields)

    class Meta:
        # Define the model and fields for the form
        model = base
        fields = '__all__'