# Generated by Django 3.1.3 on 2020-11-20 11:21
from pathlib import Path

import magic
from django.conf import settings
from django.db import migrations
from django.db import models

from paperless.db import GnuPG

STORAGE_TYPE_UNENCRYPTED = "unencrypted"
STORAGE_TYPE_GPG = "gpg"


def source_path(self) -> Path:
    if self.filename:
        fname: str = str(self.filename)
    else:
        fname = f"{self.pk:07}.{self.file_type}"
        if self.storage_type == STORAGE_TYPE_GPG:
            fname += ".gpg"

    return Path(settings.ORIGINALS_DIR) / fname


def add_mime_types(apps, schema_editor):
    Document = apps.get_model("documents", "Document")
    documents = Document.objects.all()

    for d in documents:
        with Path(source_path(d)).open("rb") as f:
            if d.storage_type == STORAGE_TYPE_GPG:
                data = GnuPG.decrypted(f)
            else:
                data = f.read(1024)

        d.mime_type = magic.from_buffer(data, mime=True)
        d.save()


def add_file_extensions(apps, schema_editor):
    Document = apps.get_model("documents", "Document")
    documents = Document.objects.all()

    for d in documents:
        d.file_type = Path(d.filename).suffix.lstrip(".")
        d.save()


class Migration(migrations.Migration):
    dependencies = [
        ("documents", "1002_auto_20201111_1105"),
    ]

    operations = [
        migrations.AddField(
            model_name="document",
            name="mime_type",
            field=models.CharField(default="-", editable=False, max_length=256),
            preserve_default=False,
        ),
        migrations.RunPython(add_mime_types, migrations.RunPython.noop),
        # This operation is here so that we can revert the entire migration:
        # By allowing this field to be blank and null, we can revert the
        # remove operation further down and the database won't complain about
        # NOT NULL violations.
        migrations.AlterField(
            model_name="document",
            name="file_type",
            field=models.CharField(
                choices=[
                    ("pdf", "PDF"),
                    ("png", "PNG"),
                    ("jpg", "JPG"),
                    ("gif", "GIF"),
                    ("tiff", "TIFF"),
                    ("txt", "TXT"),
                    ("csv", "CSV"),
                    ("md", "MD"),
                ],
                editable=False,
                max_length=4,
                null=True,
                blank=True,
            ),
        ),
        migrations.RunPython(migrations.RunPython.noop, add_file_extensions),
        migrations.RemoveField(
            model_name="document",
            name="file_type",
        ),
    ]
