# -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2016-01-24 11:40
from __future__ import unicode_literals

import re

from django.db import migrations


def set_post_timetrials(TimeTrial, post):
    text = '\n'.join([post.text] + [c.text for c in post.comment_set.all()])
    pks = []
    for mo in re.finditer(r'https?://tket.dk/5/(\d+)', text):
        pks.append(int(mo.group(1)))
    pks = sorted(set(pks))
    tts = TimeTrial.objects.filter(pk__in=pks)
    post.timetrials.set(tts)


def set_posts_timetrials(apps, schema_editor):
    Post = apps.get_model('news', 'Post')
    TimeTrial = apps.get_model('stopwatch', 'TimeTrial')
    qs = Post.objects.all()
    for post in qs:
        set_post_timetrials(TimeTrial, post)


class Migration(migrations.Migration):

    dependencies = [
        ('news', '0003_post_timetrials'),
        ('stopwatch', '0001_initial'),
    ]

    operations = [
        migrations.RunPython(set_posts_timetrials, migrations.RunPython.noop),
    ]
