import model
import sqlite3


def main():
    conn = sqlite3.connect("frony.db")
    c = conn.cursor()

    CATEGORIES = {}
    for (c_id, name, nicename) in c.execute("SELECT * FROM categories"):
        CATEGORIES[c_id] = model.Category.create(name=name, nicename=nicename)

    DESIGNS = {}
    with model.db.atomic():
        for row in c.execute("SELECT * FROM designs"):
            (id, title, description, category) = row
            DESIGNS[id] = model.Design.create(
                visible_id=id,
                title=title,
                description=description,
                category=CATEGORIES[category],
            )

    with model.db.atomic():
        for (_, filename, d_id) in c.execute("SELECT * FROM photos"):
            if d_id in DESIGNS:
                model.Photo.create(filename=filename, design=DESIGNS[d_id])

    with model.db.atomic():
        for (_, name, d_id) in c.execute("SELECT * FROM tags"):
            if d_id in DESIGNS:
                model.Tag.create(tag_name=name, design=DESIGNS[d_id])

    with model.db.atomic():
        for (_, name, text, title) in c.execute("SELECT * FROM pages"):
            model.Page.create(name=name, text=text, title=title)


if __name__ == "__main__":
    from model import *

    db.create_tables([Category, Design, Photo, Page, Tag])
    main()
