from wagtail_wordpress_import.block_builder_defaults import get_or_save_image


def header_image_processor(imported_pages, data_tag, items_cache):
    """
    imported_pages:
        Is a specific() page model queryset of all imported pages.
    data_tag:
        Is the value of the `DATA_TAG` key from the configuration above.
    items_cache:
        Is a list of dictionaries, one for each item in the XML file.
    """

    # See note above about leading _ and : characters in the XML value
    lookup = f"wp_post_meta__{data_tag}"

    for attachment in items_cache:
        # The id of the cached item used in the filter
        thumbnail_id = attachment.get("wp:post_id")

        # Filter the imported_pages for only pages that include the
        # matching thumbnail_id in the wp_post_meta field
        pages = imported_pages.filter(**{lookup: thumbnail_id})

        if pages.exists():
            # guid is the url of the image to fetch, the get_or_save_image()
            # function will fetch the image if it doesn't exist
            image_url = attachment.get("guid")
            # fix cases where the /wp prefix is missing from the image url
            if image_url.startswith("https://studentersamfundet.no/wp-content/uploads/"):
                image_url = image_url.replace(
                    "https://studentersamfundet.no/wp-content/uploads/",
                    "https://studentersamfundet.no/wp/wp-content/uploads/",
                )
            try:
                image = get_or_save_image(image_url)
            except Exception as e:
                print("Error with image", image_url, "associated with pages:", pages)
                print(e)
                continue

            print("Attaching header images to pages:", pages)
            try:
                pages.update(featured_image=image)
            except Exception:
                pass

            try:
                pages.update(logo=image)
            except Exception:
                pass
