# -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-07-17 21:26
from __future__ import unicode_literals

import datetime
import urllib.request

from django.db import migrations
from email.utils import parsedate


def mp3_based_pub_date_migration(apps, schema_editor):
    PodcastItem = apps.get_model('podcast', 'PodcastItem')
    items = PodcastItem.objects.all()
    total = len(items)

    for i, item in enumerate(items, 1):
        audio_url = item.audio_url
        print('{}/{} Processing {}'.format(i, total, audio_url))
        with urllib.request.urlopen(item.audio_url) as url:
            meta = url.info()
            parsed = parsedate(meta['Last-Modified'])
            item.pub_date = datetime.datetime(*parsed[:6])
            item.save()


class Migration(migrations.Migration):

    dependencies = [
        ('podcast', '0019_podcastsuggestion'),
    ]

    operations = [
        migrations.RunPython(mp3_based_pub_date_migration, lambda *a, **k: None),
    ]
