from .models import *
import random
import re

def populate_system_customer_fields(organisation_branch, user):
    organisation = organisation_branch.branch_organisation
    customer_types = CustomerType.objects.all()
    for customer_type in customer_types:
        fields = CustomerRegField.objects.all()
        position = 1
        for field in fields:
            data = { "org_field_label": field.field_label, "org_field_abbreviation":field.field_abbreviation,
                    "customer_type_field":customer_type, "customer_reg_field":field, "customer_type_field_added_by":user,
                    "order":position, "section":'basic', "organisation": organisation }
            CustomerTypeField.objects.create(**data)
            position += 1

def generate_member_number(branch_id):
    organisation_branch = OrganisationBranch.objects.filter(id=branch_id).first()
    member_number_prefix = None
    if organisation_branch and organisation_branch.member_number_prefix:
        member_number_prefix = str(organisation_branch.member_number_prefix)
    
    code = ""
    count = 8 - len(member_number_prefix) if member_number_prefix else 8
    for i in range(count):
        # randint generates a random number between 0,9
        code = code + str(random.randint(0, 9))

    return member_number_prefix + code if member_number_prefix else code

def get_all_customer_files(customer):
        file_list      = []
        customer_files = CustomerFiles.objects.filter(customer=customer).all()
        for customer_file in customer_files:
            file_list.append({"url":customer_file.url,"file_type":customer_file.file_type,"date_added":customer_file.date_added,"added_by":customer_file.added_by.user_staff.name})
        return file_list

def get_customer_custom_fields_meta(customer):
    if not customer:
        return []
    
    response = []
    customer_type_fields = CustomerTypeField.objects.filter(customer_type_field=customer.branch_customer_type, is_active=True)
    for customer_type_field in customer_type_fields:
        customer_field_data = CustomerFieldMeta.objects.filter(customer = customer,customer_field=customer_type_field).first()
        field_options = CustomerRegFieldOption.objects.filter(customer_reg_field_option=customer_type_field.customer_reg_field, is_active=True)

        options = []
        for option in field_options:
            options.append({
                "id":option.id,
                "field_option_label":option.field_option_label,
                "field_option_value":option.field_option_value
            })

        response.append({
            "customer_type_field_id":customer_type_field.id,
            "org_field_label": customer_type_field.org_field_label,
            "org_field_abbreviation": customer_type_field.org_field_abbreviation,
            "org_field_type":customer_type_field.customer_reg_field.field_type,
            "required": customer_type_field.required,
            "section": customer_type_field.section,
            "field_label":customer_type_field.customer_reg_field.field_label,
            "field_abbreviation":customer_type_field.customer_reg_field.field_abbreviation,
            "is_active":customer_type_field.is_active,
            "options":options,
            "customer_field_data_id":customer_field_data.id if customer_field_data else '',
            "value":(customer_field_data.value.split(',') if customer_type_field.customer_reg_field.field_type== 'checkbox' else customer_field_data.value) if customer_field_data else '',
        })

    return response

def get_customer_next_member_number(branch_id, member_number = None):
    branch = OrganisationBranch.objects.filter(id=branch_id).first()
    last_customer_member_number = None

    if member_number:
        last_customer_member_number = member_number
    else:
        customer = Customer.objects.filter(customer_branch=branch).order_by('-member_number').first()
        if customer:
            last_customer_member_number = customer.member_number

    if last_customer_member_number:
        # Extract the numerical part and convert it to an integer
        num_part = int(re.sub(r'\D', '', last_customer_member_number))

        # Increment the number
        num_part += 1

        # Format the incremented number back into the original format
        # new_number_str = f'{num_part:06d}'
        new_number_str = f'{num_part}'

        # verfiy if member number already taken  --- recursively check
        is_existing = Customer.objects.filter(member_number=new_number_str, customer_branch__branch_organisation__id=branch.branch_organisation.id).first()
        if is_existing:
            return get_customer_next_member_number(branch_id, is_existing.member_number)
        return new_number_str


def get_customer_next_old_member_number(branch_id, member_number = None):    
    branch = OrganisationBranch.objects.filter(id=branch_id).first()
    last_customer_member_number = None
    member_number_prefix = None

    if member_number:
        last_customer_member_number = member_number
    else:
        customer = Customer.objects.filter(customer_branch=branch).order_by('-old_member_number').first()
        if customer:
            last_customer_member_number = customer.old_member_number

    if branch.member_number_prefix:
        member_number_prefix = branch.member_number_prefix

    if last_customer_member_number:
        # Extract the numerical part and convert it to an integer
        num_part = int(re.sub(r'\D', '', last_customer_member_number))

        # Increment the number
        num_part += 1

        # Format the incremented number back into the original format
        # new_number_str = f'{member_number_prefix}{num_part:06d}'
        if member_number_prefix:
            new_number_str = f'{member_number_prefix}{num_part}'
        else:
            new_number_str = f'{num_part}'

        # verfiy if member number already taken  --- recursively check
        is_existing = Customer.objects.filter(old_member_number=new_number_str, customer_branch__branch_organisation__id=branch.branch_organisation.id).first()
        if is_existing:
            return get_customer_next_old_member_number(branch_id, is_existing.old_member_number)
        return new_number_str
