
import datetime

from django.conf import settings
from django.core.mail.message import EmailMessage
from django.template.loader import render_to_string 

from .models import EmailHistory, PasswordHistory
import requests


from mailerlite import MailerLiteApi



def send_activation_email(new_user, current_site):
    """ Send activation email to the user """

    subject = 'UseVoice. | Account Confirmation'
    message = render_to_string(
        'accounts/email_activation.html', 
        {'user': new_user, 'domain': current_site.domain, 'token': new_user.token('email_verification')}
    )

    mail = EmailMessage(
        subject,
        message,
        to=[new_user.email],
        from_email=settings.EMAIL_HOST_USER,
    )

    mail.content_subtype = 'html'
    mail.send()

def send_password_reset_email(user, current_site):
    """ Send password reset email to the user """
    subject = 'UseVoice. | Password Reset'
    message = render_to_string(
        'accounts/email_password_reset.html', 
        {'user': user, 'domain': current_site.domain, 'token': user.token('password_reset')}
    )
    mail = EmailMessage(
        subject,
        message,
        to=[user.email],
        from_email=settings.EMAIL_HOST_USER
    )

    mail.content_subtype = 'html'
    mail.send()


def check_email_provider_allowed(new_email):
    allowed_providers = ['gmail', 'yahoo', 'outlook', 'hotmail', 'icloud']
    email_provider = new_email.split('@')[-1].split(".")[0]
    return email_provider in allowed_providers

def check_email_domain_allowed(new_email):
    allowed_domains = ['.edu', '.gov', '.com', '.ma', '.fr']
    domain = new_email.split('@')[-1]
    return any(domain.endswith(d) for d in allowed_domains)

def email_change_limit_reached(user):
    # Check if user has reached email change limit
    # This could be done by checking the number of times the user has changed their email in the past month
    return False



def email_change_limit_reached(user):
    limit = 3  # Change this to the desired number of allowed email changes
    time_period = 30  # Change this to the desired time period (in days)
    time_threshold = datetime.datetime.now() - datetime.timedelta(days=time_period)
    email_changes = EmailHistory.objects.filter(user=user, timestamp__gte=time_threshold)
    if email_changes.count() >= limit:
        return True
    return False

def password_change_limit_reached(user):
    limit = 3  # Change this to the desired number of allowed email changes
    time_period = 7  # Change this to the desired time period (in days)
    time_threshold = datetime.datetime.now() - datetime.timedelta(days=time_period)
    email_changes = PasswordHistory.objects.filter(user=user, timestamp__gte=time_threshold)
    if email_changes.count() >= limit:
        return True
    return False

def send_confirmation_email(new_email):
    subject = 'Confirm your email change'
    # message = 'Please click the following link to confirm your email change: http://example.com/confirm-email-change/'
    # from_email = 'noreply@example.com'
    # recipient_list = [new_email]
    # send_mail(subject, message, from_email, recipient_list)

def contact_us_send_message(email,sender_name,subject,message):
    message = message
    mail = EmailMessage(
        subject = subject,
        body = message+f'\nfrom {sender_name}.',
        to=['brahim.boughanem@usevoice.io'],
        from_email=email
    )
    mail.send()

def add_sub_to_group(api_key,group_name,user_id):
    

    url = "https://api.mailerlite.com/api/v2/groups/group_name/subscribers/id/assign"

    payload = { "group_name": group_name, "id": user_id }
    headers = {
        "accept": "application/json",
        "X-MailerLite-ApiDocs": "true",
        "content-type": "application/json",
        "X-MailerLite-ApiKey": api_key
    }

    response = requests.post(url, json=payload, headers=headers)

    print(response.text)

def add_mailer_user(email, first_name, group,fields):

    """    
    Add a user to a MailerLite mailing list and assign them to a group.

    Args:
        email (str): The email address of the user.
        first_name (str): The first name of the user.
        last_name (str): The last name of the user.
        group (int): The ID of the group to which the user should be assigned.
        "fields": {
                "last_name": last_name,
                "company": activation_url,
                "city": group,
                "country": old_plan,
                "contact_us_message",
                "contact_us_subject",
                "reset_password_link",
                "new_plan",
                "old_plan",
                "email_activation_link",        
                }
    
    Returns:
        None

    Raises:
        MailerLiteException: If there is an error communicating with the MailerLite API.

    """

    # Initialize the MailerLite client using the provided API key from Django settings

    api = MailerLiteApi(settings.MAILER_LITE_KEY)
    add_new = api.groups.add_single_subscriber(
        group_id=settings.MAILER_LITE_GROUPS[group], 
        subscribers_data={
            "email": email, 
            "name": first_name,
            "fields":fields
        }, 
        autoresponders=False, 
        resubscribe=False, 
        as_json=True
    )
    return add_new


def upgrade_subscriber_group(email,first_name,fields):
    
    """
    Upgrade subscriber's group.

    Parameters:
        email (str): Subscriber's email address.
        first_name (str): Subscriber's first name.
        last_name (str): Subscriber's last name.
        activation_url (str): URL for subscriber activation.
        group (str): New subscriber group to add.
        old_plan (str): Old subscriber group to remove.

    Returns:
        None
    """

    
    api = MailerLiteApi(settings.MAILER_LITE_KEY)

    # add user to new group
    new_group = fields['new_plan'].replace(' ',"_")
    new_sub = add_mailer_user(email=email, first_name=first_name,group=new_group,fields=fields)
    
    # Add user to upgrade group
    upgraded = add_mailer_user(email, first_name, 'Upgrade_Group',fields)
    
    # Remove user from old mailer lite group
    deleted_user = api.groups.delete_subscriber(
        group_id=settings.MAILER_LITE_GROUPS[fields['old_plan'].replace(' ','_')],
        subscriber_id=new_sub['id']
    )
    return deleted_user
