import os
import sys
import sqlite3
from PIL import Image
from shutil import copyfile

args = sys.argv
the_dir = args[args.index("-d")+1]
base_count = the_dir.count("/")

conn = sqlite3.connect("toby.db")
c = conn.cursor()

print("Walking over %s..." % the_dir)
artist_ids = {}
collection_ids = {}
for root, subdirs, files in os.walk(the_dir):
    if root == the_dir:
        for subdir in subdirs:
            print("Creating artist %s..." % subdir)
            c.execute("INSERT INTO artist (name, description) VALUES (?,?)",\
                        (subdir, ""))
            artist_ids[subdir] = c.lastrowid
    else:
        artist = root[root.index("ART")+4:]
        artist = artist[0:artist.index("/")] if "/" in artist else artist
        for subdir in subdirs:
            print("Creating collection %s..." % subdir)
            c.execute("INSERT INTO collection (name, description) VALUES (?,?)",\
                        (subdir, ""))
            collection_id = c.lastrowid
            collection_ids[os.path.join(root, subdir)] = collection_id
            c.execute("INSERT INTO collection_artist (collection_id, artist_id) VALUES (?,?)",\
                        (collection_id, artist_ids[artist]))
            if root.count("/") > base_count+1:
                c.execute("INSERT INTO collection_parentage (collection_child_id, collection_parent_id) VALUES (?,?)",\
                            (collection_id, collection_ids[root]))
                
        for file in files:
            if file != ".DS_Store":
                name = file[::-1]
                name = name[name.index(".")+1:][::-1]
                final_collection_id = None
                final_order = None
                if name[0].isdigit():
                    pieces = name.split("_")
                    name = "%s, %s" % (pieces[-1], pieces[-2])
                    coordinates = pieces[:-2]
                    final_order = pieces[-2]
                    for i in range(len(coordinates)):
                        collection = root+"/"+"/".join(coordinates[:i+1])
                        if collection not in collection_ids:
                            print("Creating collection %s..." % coordinates[i])
                            c.execute("INSERT INTO collection (name, description) VALUES (?,?)",\
                                        (coordinates[i], ""))
                            collection_id = c.lastrowid
                            collection_ids[collection] = collection_id
                            c.execute("INSERT INTO collection_artist (collection_id, artist_id) VALUES (?,?)",\
                                        (collection_id, artist_ids[artist]))
                            if i != 0:
                                parent = root+"/"+"/".join(coordinates[:i])
                                parent_id = collection_ids[parent]
                                c.execute("INSERT INTO collection_parentage (collection_child_id, collection_parent_id, ordering) VALUES (?,?,?)",\
                                            (collection_id, parent_id, coordinates[i]))
                            else:
                                parent_id = collection_ids[root]
                                c.execute("INSERT INTO collection_parentage (collection_child_id, collection_parent_id, ordering) VALUES (?,?,?)",\
                                            (collection_id, parent_id, coordinates[i]))
                        if i == len(coordinates)-1:
                            final_collection_id = collection_ids[collection]
                print("Creating art %s..." % name)
                c.execute("INSERT INTO art (name, description) VALUES (?, ?)",\
                            (name, ""))
                art_id = c.lastrowid

                c.execute("INSERT INTO artist_art (artist_id, art_id) VALUES (?, ?)", \
                            (artist_ids[artist], art_id))
                collection_id = collection_ids[root] if final_collection_id == None else final_collection_id
                if final_order:
                    c.execute("INSERT INTO collection_art (collection_id, art_id, ordering) VALUES (?, ?, ?)",\
                                (collection_id, art_id, int(final_order)))
                else:
                    c.execute("INSERT INTO collection_art (collection_id, art_id) VALUES (?, ?)",\
                                (collection_id, art_id))
                c.execute("INSERT INTO url (art_id, url) VALUES (?, ?)", (art_id, file))

                filename = file[:]
                save_path = "../static/ART/%s" % filename
                if os.path.exists(save_path):
                    print("same name!!!!!!!")
                    fname, ext = os.path.splitext(filename)
                    filename = fname+"1"+ext
                    save_path = "../static/ART/%s" % filename

                fname = os.path.join(root, file)
                print("\tFilename: %s" % fname)
                print("\tSaved to: %s" % save_path)
                copyfile(fname, save_path)
                im = Image.open(fname)
                im.thumbnail((400,400))
                im.save("../static/ART/thumb_%s" % filename)

conn.commit()
conn.close()
print("Done!")

