# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2018-08-08 17:31
from __future__ import unicode_literals
from json import load
import os
from django.core import serializers

from django.db import migrations, models


TMP_FILE = '/tmp/djing_ip_field_devapp_migrate.json'


def device_backup_info(apps, _):
    Device = apps.get_model('devapp', 'Device')
    obs = Device.objects.exclude(ip_address=None).only('ip_address')
    with open(TMP_FILE, 'w') as f:
        serializers.serialize('json', obs, stream=f, fields=('ip_address',))


def device_restore_info_to_new_scheme(apps, _):
    Device = apps.get_model('devapp', 'Device')
    with open(TMP_FILE, 'r') as f:
        for device in load(f):
            Device.objects.filter(pk=device['pk']).update(ip_address=device['fields']['ip_address'])
    if os.path.isfile(TMP_FILE):
        os.remove(TMP_FILE)


class Migration(migrations.Migration):
    dependencies = [
        ('devapp', '0004_device_extra_data'),
    ]

    operations = [
        migrations.RunPython(device_backup_info),
        migrations.RemoveField(model_name='device', name='ip_address'),
        migrations.AddField(
            model_name='device',
            name='ip_address',
            field=models.GenericIPAddressField(blank=True, null=True, verbose_name='Ip address')
        ),
        migrations.RunPython(device_restore_info_to_new_scheme)
    ]
