# Generated by Django 2.2.10 on 2020-04-04 13:36

from django.db import migrations
from itertools import chain
from utils.data_migrations import stream_field_filter_map

def imageicon_to_columns(block):
    image = {
        'type': 'image',
        'value':{
            'image': block['value']['image'],
            'height': 400
        }
    }
    
    heading = {
        'type': 'heading',
        'value': {
            'title': block['value']['title']
        }
    }
    
    icons = []
    for icon in block['value']['icons']:
        icons.append({
            'title': icon['title'],
            'subtitle': icon['description'],
            'icon': icon['icon']
        })
        
    icon_group =  {
        'type': 'icons',
        'value': {
            'icons': icons
        }
    }
        
    if block['value']['image_alignment'] == "left":
        return {
            'type': 'columns',
            'value': {
                'columns':[
                    {
                        'width': 6,
                        'content': [image]
                    },
                    {
                        'width': 6,
                        'content': [
                            heading,
                            icon_group
                        ]
                    }
                ]
            }
        }
    else:
        return {
            'type': 'columns',
            'value': {
                'columns':[
                    {
                        'width': 6,
                        'content': [
                            heading,
                            icon_group
                        ]
                    },
                    {
                        'width': 6,
                        'content': [image]
                    }
                ]
            }
        }
        
def apply_to_all_pages(apps, mapper):
    HomePage = apps.get_model('home', 'HomePage')
    WebPage = apps.get_model('home', 'WebPage')
    hps = HomePage.objects.all()
    wps = WebPage.objects.all();
    for obj in chain(hps, wps):
        # There is a long-standing mistake that image-icons and image-description have swapped tags in the database.
        obj.body_en = stream_field_filter_map(obj.body_en, "image_description", mapper)
        obj.body_sv = stream_field_filter_map(obj.body_sv, "image_description", mapper)
        obj.save();

def forwards(apps, schema_editor):
    apply_to_all_pages(apps, imageicon_to_columns)


class Migration(migrations.Migration):

    dependencies = [
        ('home', '0039_auto_20200404_1529'),
    ]

    operations = [
        migrations.RunPython(forwards)
    ]
