# Generated by Django 4.2.11 on 2024-04-21 04:55

import os

from django.db import migrations
from django.core.files.base import ContentFile


def report_model_map():
    """Return a map of model_type: report_type keys."""

    return {
        'stockitem': 'testreport',
        'stocklocation': 'stocklocationreport',
        'build': 'buildreport',
        'part': 'billofmaterialsreport',
        'purchaseorder': 'purchaseorderreport',
        'salesorder': 'salesorderreport',
        'returnorder': 'returnorderreport'
    }


def forward(apps, schema_editor):
    """Run forwards migration. 
    
    - Create a new ReportTemplate instance for each existing report
    """

    # New 'generic' report template model
    ReportTemplate = apps.get_model('report', 'reporttemplate')

    count = 0

    for model_type, report_model in report_model_map().items():

        model = apps.get_model('report', report_model)

        for template in model.objects.all():
            # Construct a new ReportTemplate instance

            filename = template.template.path

            if not os.path.exists(filename):
                print(f"Migration error: Template file '{filename}' does not exist")
                continue

            if '/report/inventree/' in filename:
                # Do not migrate internal report templates
                continue
        
            filename = os.path.basename(filename)
            filedata = template.template.open('r').read()

            name = template.name
            offset = 1

            # Prevent duplicate names during migration
            while ReportTemplate.objects.filter(name=name, model_type=model_type).exists():
                name = template.name + f"_{offset}"
                offset += 1

            ReportTemplate.objects.create(
                name=name,
                template=ContentFile(filedata, filename),
                model_type=model_type,
                description=template.description,
                revision=template.revision,
                filters=template.filters,
                filename_pattern=template.filename_pattern,
                enabled=template.enabled,
                page_size=template.page_size,
                landscape=template.landscape,
            )

            count += 1

    if count > 0:
        print(f"Migrated {count} report templates to new ReportTemplate model.")


def reverse(apps, schema_editor):
    """Run reverse migration.

    - Delete any ReportTemplate instances in the database
    """
    ReportTemplate = apps.get_model('report', 'reporttemplate')

    n = ReportTemplate.objects.count()

    if n > 0:
        for item in ReportTemplate.objects.all():
            item.template.delete()
            item.delete()
        
        print(f"Deleted {n} ReportTemplate objects and templates")


class Migration(migrations.Migration):

    dependencies = [
        ('report', '0022_reporttemplate'),
    ]

    operations = [
        migrations.RunPython(forward, reverse_code=reverse)
    ]
