# Generated by Django 3.0.2 on 2020-03-13 16:51
import os
import csv

from django.db import migrations, models


COURSE_DATA_PATH = os.path.join(os.path.dirname(os.path.dirname(
    os.path.abspath(__file__)
)), 'course_data')


def add_drive_links(apps, schema_editor):
    Course = apps.get_model('courses', 'Course')

    with open(os.path.join(COURSE_DATA_PATH, 'course_links.csv')) as f:
        csv_reader = csv.reader(f)
        for row in csv_reader:
            code, link = row
            course = Course.objects.get(code=code)
            course.drive_link = link
            course.save()


def remove_drive_links(apps, schema_editor):
    Course = apps.get_model('courses', 'Course')

    with open(os.path.join(COURSE_DATA_PATH, 'course_links.csv')) as f:
        csv_reader = csv.reader(f)
        for row in csv_reader:
            code, _ = row
            course = Course.objects.get(code=code)
            course.drive_link = None
            course.save()


def add_PQ_as_course(apps, schema_editor):
    Course = apps.get_model('courses', 'Course')
    Lecturer = apps.get_model('people', 'Lecturer')

    all_lecturers = Lecturer.objects.create(
        title='',
        last_name='Lecturers',
        first_name='All'
    )
    pq = Course.objects.create(
        code='PQs',
        title='Past Questions',
        description='Containing Past Questions from various levels.',
        category='3',
    )

    pq.lecturers.add(all_lecturers)


def remove_PQ_as_course(apps, schema_editor):
    Course = apps.get_model('courses', 'Course')
    Lecturer = apps.get_model('people', 'Lecturer')

    Course.objects.filter(code='PQs').delete()
    Lecturer.objects.filter(last_name='Lecturers', first_name='All').delete()


class Migration(migrations.Migration):

    dependencies = [
        ('courses', '0006_added_snapchat_field'),
    ]

    operations = [
        migrations.AlterField(
            model_name='course',
            name='units',
            field=models.PositiveIntegerField(null=True)
        ),
        migrations.AlterField(
            model_name='course',
            name='description',
            field=models.TextField(blank=True)
        ),
        migrations.RunPython(
            add_PQ_as_course,
            remove_PQ_as_course
        ),
        migrations.RunPython(
            add_drive_links,
            remove_drive_links,
        )
    ]
