import logging

import peewee as pw

from defence360agent.utils import importer

MalwareScanResourceType = importer.get(
    module="imav.malwarelib.config",
    name="MalwareScanResourceType",
    default=None,
)

logger = logging.getLogger(__name__)


def migrate(migrator, database, fake=False, **kwargs):
    MalwareHits = migrator.orm["malware_hits"]
    migrator.add_fields(
        MalwareHits,
        resource_type=pw.CharField(
            null=False,
            default=MalwareScanResourceType.FILE.value,
            constraints=[
                pw.Check(
                    "resource_type in {}".format(
                        (
                            MalwareScanResourceType.DB.value,
                            MalwareScanResourceType.FILE.value,
                        )
                    )
                )
            ],
        ),
        app_name=pw.CharField(null=True),
        db_host=pw.CharField(null=True),
        db_port=pw.CharField(null=True),
        db_name=pw.CharField(null=True),
    )
    MalwareScan = migrator.orm["malware_scans"]
    migrator.add_fields(
        MalwareScan,
        resource_type=pw.CharField(
            null=False,
            default=MalwareScanResourceType.FILE.value,
            constraints=[
                pw.Check(
                    "resource_type in {}".format(
                        (
                            MalwareScanResourceType.DB.value,
                            MalwareScanResourceType.FILE.value,
                        )
                    )
                )
            ],
        ),
    )
    migrator.rename_field(MalwareScan, "total_files", "total_resources")


def rollback(migrator, database, fake=False, **kwargs):
    MalwareHits = migrator.orm["malware_hits"]
    migrator.remove_fields(MalwareHits, "resource_type")
