from __future__ import annotations

import io

from django.contrib.auth import get_user_model
from django.core.files.uploadedfile import SimpleUploadedFile
from PIL import Image as PilImage
from wagtail.images import get_image_model
from wagtail.models import Collection, Page, Site

from ..models import MobileApp


def make_test_image(filename="icon.png", size=(512, 512), color=(0, 120, 255)):
    file_obj = io.BytesIO()
    image = PilImage.new("RGBA", size, color)
    image.save(file_obj, format="PNG")
    file_obj.seek(0)
    return SimpleUploadedFile(filename, file_obj.read(), content_type="image/png")


def create_wagtail_image(title="Icon", size=(512, 512)):
    image_model = get_image_model()
    collection = Collection.get_first_root_node()
    return image_model.objects.create(
        title=title,
        file=make_test_image(
            filename=f"{title.lower().replace(' ', '-')}.png", size=size
        ),
        collection=collection,
    )


def create_site(hostname="example.com", site_name="Example", is_default=True):
    if is_default:
        Site.objects.update(is_default_site=False)
    root = Page.get_first_root_node()
    slug = hostname.replace(".", "-")
    home = root.add_child(instance=Page(title=site_name, slug=slug))
    site = Site.objects.create(
        hostname=hostname,
        site_name=site_name,
        root_page=home,
        is_default_site=is_default,
        port=443,
    )
    return site


def create_mobile_app(site, **overrides):
    icon = overrides.pop("icon", create_wagtail_image())
    splash_image = overrides.pop(
        "splash_image", create_wagtail_image(title="Splash", size=(2048, 2048))
    )
    defaults = {
        "enable_pwa": True,
        "enable_android": True,
        "enable_ios": True,
        "name": "Example App",
        "short_name": "Example",
        "app_id": "com.mandelblog.example",
        "app_version": "1.0.0",
        "build_number": 1,
        "description": "Example app description",
        "theme_color": "#112233",
        "background_color": "#ffffff",
        "foreground_color": "#ffffff",
        "accent_color": "#0d6efd",
        "status_bar_color": "#112233",
        "navigation_bar_color": "#ffffff",
        "start_url": "/",
        "scope": "/",
        "offline_url": "",
        "display_mode": "standalone",
        "orientation": "any",
        "icon": icon,
        "splash_image": splash_image,
    }
    defaults.update(overrides)
    return MobileApp.objects.create(site=site, **defaults)


def create_staff_user(username="editor"):
    return get_user_model().objects.create_user(
        username=username,
        password="password",
        is_staff=True,
        is_superuser=True,
    )
