import json
import logging
import urllib.request

import bleach
import requests
from django.conf import settings
from django.core.files import File
from django.utils.translation import gettext_lazy
from wagtail.admin.panels import CommentPanel, FieldPanel, HelpPanel, MultiFieldPanel
from wagtail.images.edit_handlers import FieldPanel
from wagtail.images.models import Image
from wagtail.models import Page

from tuning import admin_help

logger = logging.getLogger()


def create_image_from_url(url, filename):
    img_data = urllib.request.urlretrieve(url)
    img_obj = Image(title=filename)
    img_obj.file.save(filename, File(open(img_data[0], "rb")))
    img_obj.save()
    return img_obj


def get_subpage_url(page, dest_page_type):
    try:
        return page.get_descendants().type(dest_page_type).live().first().get_url()
    except (Page.DoesNotExist, AttributeError):
        return "#"


def make_promote_panels(
    help_content=None, *, seo_title=True, search_description=True, search_image=True
):
    if help_content is None:
        help_content = admin_help.build(
            admin_help.NO_SEO_TITLE, admin_help.NO_SEARCH_IMAGE
        )

    panels = [FieldPanel("slug")]
    if seo_title:
        panels.append(FieldPanel("seo_title"))
    if search_description:
        panels.append(FieldPanel("search_description"))
    if search_image:
        panels.append(FieldPanel("search_image"))
    panels.append(HelpPanel(help_content))
    panels.append(CommentPanel())

    return [MultiFieldPanel(panels, gettext_lazy("Common page configuration"))]


def subscribe_to_newsletter(email, news_id, source):
    payload = {
        "email": email,
        "news_id": news_id,
        "source": source,
        "verify_email": 1,
    }
    response = requests.post(
        settings.NALODENI_API_NEWS_SUBSCRIBE_URL,
        data=json.dumps(payload),
        auth=tuple(settings.NALODENI_API_CREDENTIALS.split(":")),
    )
    if response.status_code != 200:
        logger.error(
            "Failed to subscribe!",
            extra={"payload": payload, "response": response.text},
        )


def strip_all_html_tags(value: str):
    """Drop all HTML tags from given value.

    :param value: string to sanitize
    """
    return bleach.clean(value, tags=[], attributes=[], strip=True, strip_comments=True)


def trim_to_length(value: str, max_length: int = 150):
    """Trim value to max length shall it exceed it.

    :param value: input string
    :param max_length: max allowed length
    """
    if len(value) > max_length:
        return value[:max_length] + "..."
    return value