from django import template
from django.conf import settings
from django.utils.translation import get_language
import os
import json
from django.templatetags.static import static

register = template.Library()

@register.filter
def get_item(dictionary, key):
    """
    Get value from dictionary by key.

    Example: {{ my_dict|get_item:'my_key' }}
    """
    return dictionary.get(key)

@register.filter
def get_form_field(form, field_name):
    """
    Get form field by name.

    Example: {{ my_form|get_form_field:'my_field' }}
    """
    try:
        return form[field_name]
    except KeyError:
        return None

@register.filter
def check_tags(tag, field_tags):
    """
    Check if tag is in comma-separated list.

    Example: {% if 'my_tag'|check_tags:'my_tag,other_tag' %}Tag is present{% endif %}
    """
    return tag.lower() in field_tags.lower()

@register.simple_tag
def pfp_exist(file_path):
    """
    Checks if the file exists and returns True or False.

    :param file_path: The path to the file to check.
    :return: True if the file exists, False otherwise.
    """
    absolute_path = os.path.join(settings.BASE_DIR, "cms", file_path)
    return os.path.exists(absolute_path)

@register.filter
def format_mult_val_title_name(value):
    """
    Converts strings like 'service_1 {{SHOW}}' to 'Service 1'.
    Removes any commands like {{SHOW}}
    """
    # Remove all underscores
    formatted_string = value.replace('_', ' ')
    
    # Remove all commands
    commands = ["{{SHOW}}", "{{EXPANDABLE}}"]
    for command in commands:  
        formatted_string = formatted_string.replace(command, "") if command in formatted_string else formatted_string
    
    # Pass through title argument
    formatted_string = formatted_string.title()
    return formatted_string

@register.filter
def check_string_show(string):
    return "{{SHOW}}" in string

@register.filter
def check_string_expand(string):
    return "{{EXPANDABLE}}" in string

@register.filter
def get_translated_sidebar_label(label_name):
    lang_code = get_language()
    
    # Define the path to the locale folder and the specific JSON file
    locale_folder = os.path.join(settings.BASE_DIR, 'cms', 'locale', lang_code)
    json_file_path = os.path.join(locale_folder, f'labels_{lang_code}.json')

    # Check if the JSON file exists
    if os.path.exists(json_file_path):
        with open(json_file_path, 'r', encoding='utf-8') as json_file:
            labels = json.load(json_file)
            
            # Loop through the labels to find the matching original label
            for label in labels:
                if label.get('original') == label_name:
                    return label.get('translated')

    # Return the original label name if no translation is found
    return label_name


@register.simple_tag(takes_context=True)
def print_variable(context, file):
    """
    A tag that takes context and prints the value of the variable.
    """
    # Get parent path
    parent_page = context.get("table_attr", "")
    
    parent_local_path = os.path.join(settings.WEBSITE_MEDIA_ROOT, parent_page)
    parent_static_path = os.path.join("website", 'img', parent_page)
    
    image_formats = ['jpg', 'jpeg', 'png', 'webp']

    # Get image formate
    for img_format in image_formats:
        # Construct the full file path
        file_path = os.path.join(parent_local_path, f"{file}.{img_format}")

        # Check if the file exists
        if os.path.exists(file_path):
            image_format = img_format
    
    file = f"{file}.{image_format}"
    
    full_local_path = os.path.join(parent_local_path, file)
    full_static_path = os.path.join(parent_static_path, file)

    if os.path.exists(full_local_path):
        return static(full_static_path)
    
    else:
        common_path = os.path.join(parent_static_path, 'img', '__common__')
        
        if os.path.exists(os.path.join(common_path, file)):
            return static(os.path.join(common_path, file))
        
        else:
            return static(os.path.join("cms", 'img', 'defaults/default_image.png'))