import logging
from datetime import datetime, timedelta

import peewee as pw

from defence360agent.utils import importer
from defence360agent.utils import split_for_chunk

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

logger = logging.getLogger(__name__)

types = (
    MalwareScanType.ON_DEMAND,
    MalwareScanType.REALTIME,
    MalwareScanType.MALWARE_RESPONSE,
    MalwareScanType.BACKGROUND,
    MalwareScanType.RESCAN,
)


def migrate(migrator, database, fake=False, **kwargs):
    MalwareHit = migrator.orm["malware_hits"]
    MalwareScan = migrator.orm["malware_scans"]

    date = (datetime.now() - timedelta(days=30)).timestamp()

    hits_to_delete = list(
        MalwareHit.select(MalwareHit.id)
        .join(MalwareScan)
        .where(MalwareScan.started < date)
    )

    for chunk in split_for_chunk(hits_to_delete):
        sql, params = MalwareHit.delete().where(MalwareHit.id.in_(chunk)).sql()
        migrator.sql(sql, params)

    sql, params = MalwareScan.delete().where(MalwareScan.started < date).sql()
    migrator.sql(sql, params)

    migrator.change_fields(
        MalwareScan,
        type=pw.CharField(
            null=False, constraints=[pw.Check("type in {}".format(types))]
        ),
    )


def rollback(migrator, database, fake=False, **kwargs):
    pass
