# Generated by Django 5.2.4 on 2025-09-14 13:15

from django.db import migrations
from .. import settings


class Migration(migrations.Migration):
    dependencies = [
        ('tinywiki', '0001_initial'),
    ]

    @staticmethod
    def init_tinywiki_user(apps, schema_editor):
        from django.contrib.auth import get_user_model
        get_user_model().objects.create_user(**settings.TINYWIKI_USER_CONFIG)

    @staticmethod
    def init_tinywiki_groups_and_permissions(apps, schema_editor):
        from ..models import Page
        from django.contrib.auth.models import Group, Permission
        from django.contrib.contenttypes.models import ContentType

        PERMISSIONS = [
            'tinywiki-read-all',
            'tinywiki-delete',
            'tinywiki-create',
            'tinywiki-create-system',
            'tinywiki-edit',
            'tinywiki-edit-system',
            'tinywiki-edit-all',
            'tinywiki-delete-all',
            'tinywiki-delete-system',
        ]

        GROUPS = [
            ('tinywiki-moderator', ('tinywiki-read-all',
                                    'tinywiki-delete-all',
                                    'tinywiki-edit-all',
                                    'tinywiki-create')),
            ('tinywiki-author', ('tinywiki-create',
                                 'tinywiki-edit',
                                 'tinywiki-delete')),
            ('tinywiki-reader', ('tinywiki-read-all',)),
            ('tinywiki-admin', ('tinywiki-read-all',
                                'tinywiki-create',
                                'tinywiki-create-system',
                                'tinywiki-delete-all',
                                'tinywiki-delete-system',
                                'tinywiki-edit-all',
                                'tinywiki-edit-system'))
        ]

        perm_mapping = {}
        content_type = ContentType.objects.get_for_model(Page)
        for perm in PERMISSIONS:
            permission = Permission.objects.create(codename=perm,content_type=content_type)
            perm_mapping[perm] = permission

        for grp, perms in GROUPS:
            group = Group.objects.create(name=grp)
            for perm in perms:
                group.permissions.add(perm_mapping[perm])

    @staticmethod
    def init_builtin_pages(apps, schema_editor):
        from ..models import Page, BuiltinPages
        from ..enums import WikiContentType, WikiPageStatus
        from pathlib import Path
        import json

        page_path = Path(__file__).resolve().parent / "pages"
        json_file = page_path / "pages.json"

        if json_file.is_file():
            with open(json_file, "rt", encoding="utf-8") as ifile:
                data = json.loads(ifile.read())

            version = data["version"]
            app = 'tinywiki'
            prefix = data['prefix']

            for slug, spec in data['pages'].items():
                filename = page_path / spec['file']
                with open(filename, "rt", encoding="utf-8") as ifile:
                    content = ifile.read()

                Page.objects.create(slug=slug,
                                    title=spec['title'],
                                    status_data=WikiPageStatus.from_string(spec['status']).value,
                                    content_type_data=WikiContentType.from_string(spec['content_type']).value,
                                    content=content)

            BuiltinPages.objects.create(app=app, prefix=prefix, version=version)

    @staticmethod
    def init_builtin_images(apps, schema_edit):
        from pathlib import Path
        from ..models import Image, BuiltinImages
        from django.core.files.images import ImageFile
        import json

        image_dir = Path(__file__).resolve().parent / "images"
        images_json_file = image_dir / "images.json"

        if not images_json_file.is_file():
            return

        with open(images_json_file, "rt", encoding="utf-8") as ifile:
            images_data = json.loads(ifile.read())

        version = images_data['version']
        app = 'tinywiki'
        prefix = images_data['prefix']

        for slug, _spec in images_data['images'].items():
            spec = dict(_spec)
            image_basename = spec['image']
            image_filename = image_dir / spec["image"]
            spec['slug'] = slug
            del spec['image']

            img = Image(**spec)
            with open(image_filename,"rb") as ifile:
                img_file = ImageFile(ifile,image_basename)
                img.image.save(image_basename,img_file)
            img.save()

        BuiltinImages.objects.create(app=app, prefix=prefix, version=version)


    operations = [
        migrations.RunPython(init_tinywiki_groups_and_permissions),
        migrations.RunPython(init_tinywiki_user),
        migrations.RunPython(init_builtin_images),
        migrations.RunPython(init_builtin_pages),
    ]
