import time

from peewee import CharField, Check, CompositeKey, IntegerField, Model


class TMPMalwareIgnorePath(Model):
    class Meta:
        db_table = "tmp_malware_ignore_path"
        primary_key = CompositeKey("path", "resource_type")

    CACHE = None

    path = CharField()
    resource_type = CharField(
        null=False, constraints=[Check("resource_type in ('file','db')")]
    )
    added_date = IntegerField(null=False, default=lambda: int(time.time()))


def migrate(migrator, *_, fake=False, **__):
    change_malware_ignore_path_model(migrator)


def change_malware_ignore_path_model(migrator):
    migrator.create_model(TMPMalwareIgnorePath)
    migrator.sql(
        "INSERT INTO tmp_malware_ignore_path(path,added_date,resource_type) "
        "SELECT path,added_date,'file' FROM malware_ignore_path"
    )
    migrator.sql("DROP TABLE malware_ignore_path")
    migrator.sql(
        "ALTER TABLE tmp_malware_ignore_path RENAME TO malware_ignore_path"
    )
    migrator.sql(
        "CREATE INDEX malware_ignore_path_resource_type "
        "ON malware_ignore_path (resource_type)"
    )


def rollback(*_, **__):
    pass
