# -*- coding: utf-8 -*-
# Generated by Django 1.11.16 on 2018-11-20 13:12
from __future__ import unicode_literals

from django.db import migrations


def migrate_resource(apps, schema_editor):
    Resource = apps.get_model('marketplace', 'Resource')
    OrderItem = apps.get_model('marketplace', 'OrderItem')
    ComponentQuota = apps.get_model('marketplace', 'ComponentQuota')
    ComponentUsage = apps.get_model('marketplace', 'ComponentUsage')

    class OrderItemStates(object):
        PENDING = 1
        EXECUTING = 2
        DONE = 3
        ERRED = 4

    class ResourceStates(object):
        CREATING = 1
        OK = 2
        ERRED = 3
        UPDATING = 4
        TERMINATING = 5
        TERMINATED = 6

    StatesMap = {
        OrderItemStates.PENDING: ResourceStates.CREATING,
        OrderItemStates.EXECUTING: ResourceStates.CREATING,
        OrderItemStates.DONE: ResourceStates.OK,
        OrderItemStates.ERRED: ResourceStates.ERRED,
    }

    for item in OrderItem.objects.all():
        item.limits = {q.component.type: q.limit for q in item.quotas.all()}
        resource, _ = Resource.objects.get_or_create(
            object_id=item.object_id,
            content_type=item.content_type,
            plan=item.plan,
            attributes=item.attributes,
            project=item.order.project,
            offering=item.offering,
            limits=item.limits,
            state=StatesMap[item.state],
        )
        item.resource = resource
        item.save()

    for obj in ComponentQuota.objects.all():
        obj.resource = obj.order_item.resource
        obj.save()

    for obj in ComponentUsage.objects.all():
        obj.resource = obj.order_item.resource
        obj.save()


class Migration(migrations.Migration):

    dependencies = [
        ('marketplace', '0045_add_resource'),
    ]

    operations = [
        migrations.RunPython(migrate_resource, elidable=True)
    ]
