"""Webapp utils."""

from django.utils import timezone
import sendgrid
from sendgrid.helpers.mail import *

from datetime import timedelta
import logging
from django.template.loader import render_to_string
from django.core.files.base import ContentFile
import base64
import uuid
from sikweb.settings import FRONTEND_URL, EMAIL_API_KEY, DEFAULT_EMAIL_FROM_ADDR, ENABLE_AUTOMATIC_EMAILS
import imghdr
import markdown


def get_file_extension(file_name, decoded_file):
    extension = imghdr.what(file_name, decoded_file)
    extension = "jpg" if extension == "jpeg" else extension
    return extension


def decode_base64_file(data):
    # Check if this is a base64 string
    if isinstance(data, str):
        # Check if the base64 string is in the "data:" format
        if 'data:' in data and ';base64,' in data:
            # Break out the header from the base64 content
            header, data = data.split(';base64,')

        # Try to decode the file. Return validation error if it fails.
        try:
            decoded_file = base64.b64decode(data)
        except TypeError:
            TypeError('invalid_image')

        # Generate file name:
        file_name = str(uuid.uuid4())

        # Get the file name extension:
        file_extension = get_file_extension(file_name, decoded_file)

        complete_file_name = "%s.%s" % (file_name, file_extension, )

        return ContentFile(decoded_file, name=complete_file_name)


def month_from_now():
    """Return date one month from now."""
    return timezone.now() + timedelta(days=30)


def send_email(to, subject, body, html=False):
    if not ENABLE_AUTOMATIC_EMAILS:
        logging.debug("Skipping email")
        logging.debug(f"to: {to}")
        logging.debug(f"subject: {subject}")
        logging.debug(f"body: {body}")
        return

    from_email = Email(DEFAULT_EMAIL_FROM_ADDR)
    to_email = To(to)
    sub = Subject(subject)

    if (html):
        content = HtmlContent(body)
    else:
        content = PlainTextContent(body)

    mail = Mail(from_email, to_email, sub, content)

    try:
        sg = sendgrid.SendGridAPIClient(EMAIL_API_KEY)
        response = sg.client.mail.send.post(request_body=mail.get())

        if response.status_code != 202:
            raise Exception(f'Failed to send email: {response.body}')

    except Exception as ex:
        logging.exception('Failed to send email.')


def send_signup_email(to, subject, id, uuid, content):
    message = render_to_string(
        'webapp:signup_email.html', {
            'url': f"https://{FRONTEND_URL}/signup/edit/{id}/{uuid}",
            'content': markdown.markdown(content),
        }
    )

    return send_email(to, subject, message, True)


def admin_send_email_signupees(list, subject, content):
    for to in list:
        send_email(to.email, subject, markdown.markdown(content), True)
