# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2018-08-08 14:48
from __future__ import unicode_literals
from ipaddress import ip_address, ip_network
from json import load
import os
from django.core import serializers

import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
import re
from ip_pool.models import NetworkModel, IpLeaseModel


TMP_FILE = '/tmp/djing_ip_field_abonapp_migrate.json'


def backup_info(apps, _):
    print('\tbackup_info')
    Abon = apps.get_model('abonapp', 'Abon')
    obs = Abon.objects.exclude(ip_address=None).only('ip_address', 'is_dynamic_ip')
    with open(TMP_FILE, 'w') as f:
        serializers.serialize('json', obs, stream=f, fields=('ip_address', 'is_dynamic_ip'))
    print('\tEND backup_info')


def restore_info_to_new_scheme(apps, _):
    print('\trestore_info_to_new_scheme')
    Abon = apps.get_model('abonapp', 'Abon')
    with open(TMP_FILE, 'r') as f:
        for abon in load(f):
            ip_addr = abon['fields'].get('ip_address')
            if ip_addr is None:
                continue
            ip_addr = ip_address(ip_addr)
            is_dynamic_ip = abon['fields'].get('is_dynamic_ip')
            if is_dynamic_ip is None:
                continue

            try:
                ip_lease = IpLeaseModel.objects.get(ip=str(ip_addr))
            except IpLeaseModel.DoesNotExist:
                net = ip_network((ip_addr, 24), strict=False)
                try:
                    network = NetworkModel.objects.get(network=str(net))
                except NetworkModel.DoesNotExist:
                    ip_max = ip_address(int(ip_addr) | 0xfe)
                    ip_min = next(net.hosts())
                    network = NetworkModel.objects.create(
                        network=str(net),
                        kind='inet',
                        description='Пользовательский диапазон',
                        ip_start=str(ip_min),
                        ip_end=str(ip_max)
                    )
                ip_lease = IpLeaseModel.objects.create_from_ip(
                    ip=str(ip_addr),
                    net=network,
                    is_dynamic=is_dynamic_ip
                )
            abon_db = Abon.objects.filter(pk=abon['pk']).first()
            if abon_db is not None:
                abon_db.ip_addresses.add(ip_lease.pk)
                print('\tUser %s: %s updated' % (abon_db.username, abon_db.fio))
            else:
                print('\tUser with pk=%s not found' % abon['pk'])
    print('\tEND restore_info_to_new_scheme')
    if os.path.isfile(TMP_FILE):
        os.remove(TMP_FILE)


class Migration(migrations.Migration):

    dependencies = [
        ('ip_pool', '0001_initial'),
        ('abonapp', '0001_initial'),
    ]

    operations = [
        migrations.RunPython(backup_info),
        migrations.AlterModelOptions(
            name='abon',
            options={'ordering': ('fio',), 'permissions': (('can_buy_tariff', 'Buy service perm'), ('can_view_passport', 'Can view passport'), ('can_add_ballance', 'fill account'), ('can_ping', 'Can ping')), 'verbose_name': 'Abon', 'verbose_name_plural': 'Abons'},
        ),
        migrations.AlterModelOptions(
            name='abonlog',
            options={'ordering': ('-date',), 'permissions': (('can_view_abonlog', 'Can view subscriber logs'),)},
        ),
        migrations.AlterModelOptions(
            name='abonstreet',
            options={'ordering': ('name',), 'verbose_name': 'Street', 'verbose_name_plural': 'Streets'},
        ),
        migrations.AlterModelOptions(
            name='abontariff',
            options={'ordering': ('time_start',), 'permissions': (('can_complete_service', 'finish service perm'),), 'verbose_name': 'Abon service', 'verbose_name_plural': 'Abon services'},
        ),
        migrations.AlterModelOptions(
            name='allpaylog',
            options={'ordering': ('-date_action',)},
        ),
        migrations.AlterModelOptions(
            name='alltimepaylog',
            options={'ordering': ('-date_add',)},
        ),
        migrations.AlterModelOptions(
            name='passportinfo',
            options={'ordering': ('series',), 'verbose_name': 'Passport Info', 'verbose_name_plural': 'Passport Info'},
        ),
        migrations.AlterModelOptions(
            name='periodicpayforid',
            options={'ordering': ('last_pay',)},
        ),
        migrations.RemoveField(
            model_name='abon',
            name='extra_fields',
        ),
        migrations.RemoveField(
            model_name='abon',
            name='ip_address',
        ),
        migrations.AddField(
            model_name='abon',
            name='ip_addresses',
            field=models.ManyToManyField(to='ip_pool.IpLeaseModel', verbose_name='Ip addresses'),
        ),
        migrations.AlterField(
            model_name='additionaltelephone',
            name='telephone',
            field=models.CharField(max_length=16, validators=[django.core.validators.RegexValidator('^(\\+[7,8,9,3]\\d{10,11})?$')], verbose_name='Telephone'),
        ),
        migrations.AlterField(
            model_name='passportinfo',
            name='abon',
            field=models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='abonapp.Abon'),
        ),
        migrations.AlterField(
            model_name='passportinfo',
            name='distributor',
            field=models.CharField(max_length=64, verbose_name='Distributor'),
        ),
        migrations.AlterField(
            model_name='passportinfo',
            name='number',
            field=models.CharField(max_length=6, validators=[django.core.validators.RegexValidator(re.compile('^-?\\d+\\Z', 32), code='invalid', message='Enter a valid integer.')], verbose_name='Pasport number'),
        ),
        migrations.AlterField(
            model_name='passportinfo',
            name='series',
            field=models.CharField(max_length=4, validators=[django.core.validators.RegexValidator(re.compile('^-?\\d+\\Z', 32), code='invalid', message='Enter a valid integer.')], verbose_name='Pasport serial'),
        ),
        migrations.DeleteModel(
            name='ExtraFieldsModel',
        ),
        migrations.RunPython(restore_info_to_new_scheme)
    ]
