# Generated by Django 2.2.8 on 2021-06-01 09:38

from django.db import migrations, models
import logging

logger = logging.getLogger(__name__)


def move_serial_device_handlers(apps, schema_editor):
    # We can't import the Person model directly as it may be a newer
    # version than this migration expects. We use the historical version.
    SerialDevice = apps.get_model("serial", "SerialDevice")
    SerialHandler = apps.get_model("serial", "SerialDeviceHandler")
    Handler = apps.get_model("pyscada", "DeviceHandler")
    items = []
    count = 0
    for item in SerialHandler.objects.using(schema_editor.connection.alias).all():
        items.append(Handler(name=item.name,
                             handler_class=item.handler_class,
                             handler_path=item.handler_path,
                             ))
        count += 1

    Handler.objects.bulk_create(items)

    devices = []
    for item in SerialHandler.objects.using(schema_editor.connection.alias).all():
        for device in SerialDevice.objects.using(schema_editor.connection.alias).all():
            if device.instrument == item:
                device.instrument_handler = Handler.objects.filter(name=item.name,
                                                                   handler_class=item.handler_class,
                                                                   handler_path=item.handler_path,).first()
                devices.append(device)

        # item.delete()
    SerialDevice.objects.bulk_update(devices, ['instrument_handler'])

    logger.info('moved %d SerialHandler\n' % count)


class Migration(migrations.Migration):

    dependencies = [
        ('pyscada', '0079_devicehandler'),
        ('serial', '0009_serialdevice_instrument_handler')
    ]

    operations = [
        migrations.RunPython(move_serial_device_handlers, reverse_code=migrations.RunPython.noop),
    ]
