# -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2016-01-31 16:13
from __future__ import unicode_literals

from django.db import migrations
import json


def fill_from_mock(apps, schema_editor):
    try:
        with open('mock/project/list.json') as f:
            content = f.read()
            f.close()
    except IOError:
        content = '[]'
    records = json.loads(content)

    Project = apps.get_model("project", "Project")
    Project.objects.all().delete()
    Image = apps.get_model("image", "Image")
    Tag = apps.get_model("tag", "Tag")

    for record in records:
        project, created = Project.objects.get_or_create(pk=record['id'], name=record['name'], title=record['title'],
                                                         description=record['description'], url=record['url'],
                                                         type=record['type'],
                                                         html=record['html'],
                                                         markdown=record['markdown'], text=record['text'])

        try:
            tagRecords = record['tags']
        except:
            tagRecords = []

        for tagRecord in tagRecords:
            tag, tagCreated = Tag.objects.get_or_create(text=tagRecord['text'])
            project.tags.add(tag)


        try:
            imageRecords = record['images']
        except:
            imageRecords = []

        for imageRecord in imageRecords:
            image, imageCreated = Image.objects.get_or_create(src=imageRecord['src'])
            project.images.add(image)

        project.save()


class Migration(migrations.Migration):
    dependencies = [
        ('project', '0001_initial'),
    ]

    operations = [
        migrations.RunPython(fill_from_mock),
    ]
