# Generated by Django 2.1.7 on 2019-03-15 22:16

from django.db import migrations
from django.conf import settings
import os.path
import csv
import datetime
from django.core.files import File
from django.utils.text import slugify


def load_book_data(apps, schema_editor):
    """ Read a CSV file full of free online books and insert them into the database. """
    Book = apps.get_model('core', 'Book')
    Author = apps.get_model('core', 'Author')
    Category = apps.get_model('core', 'Category')


    datapath = os.path.join(settings.BASE_DIR, 'initial_data')
    datafile = os.path.join(datapath, 'class_list_of_books.csv')
    with open(datafile) as file:
        reader = csv.DictReader(file) 
        for row in reader:
            #set book_title so that you can only add books that have not already been added
            book_title = row['title']

            author, _ = Author.objects.get_or_create(author=row['author'])
            category, _ = Category.objects.get_or_create(book_category=row['book_category'], slug=slugify(row['book_category'])[:50])

            if Book.objects.filter(title=book_title).count():
                return
            #but if the title isnt there then make a new book
            # the first part of the Book() tells what field to put it in
            #the second part is the value to put in that field
            book = Book(
                title=row['title'],
                description=row['description'],
                access_online=row['access_online'],
                slug=slugify(row['title'])[:50],
            )
            book.save()
            book.book_category.set([category])
            book.author.set([author])

            book.save()



class Migration(migrations.Migration):

    dependencies = [
        ('core', '0026_auto_20190315_1811'),
    ]

    operations = [migrations.RunPython(load_book_data)
    ]
