# -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2018-05-11 12:04
from __future__ import unicode_literals

from django.db import migrations, models


def add_values_to_null_lunids(apps, schema_editor):
    target_model = apps.get_model('services', 'iscsitarget')
    for target in target_model.objects.all():
        used_lunids = [
            o.iscsi_lunid for o in target.iscsitargettoextent_set.all().exclude(
                iscsi_lunid=None
            )
        ]
        cur_lunid = 0
        for t2e in target.iscsitargettoextent_set.all().extra({
            'null_first': 'iscsi_lunid IS NULL',
        }).order_by('null_first', 'iscsi_lunid'):
            if t2e.iscsi_lunid is None:
                while cur_lunid in used_lunids:
                    cur_lunid += 1
                t2e.iscsi_lunid = cur_lunid
                used_lunids.append(cur_lunid)
                t2e.save()


class Migration(migrations.Migration):

    dependencies = [
        ('services', '0019_remove_afp_srv_home'),
    ]

    operations = [
        migrations.RunPython(
            add_values_to_null_lunids
        ),
        migrations.AlterField(
            model_name='iscsitargettoextent',
            name='iscsi_lunid',
            field=models.IntegerField(verbose_name='LUN ID'),
        ),
    ]
