#!/usr/bin/env python3

import rdflib
import yaml

from rdflib import BNode, Graph, Literal, Namespace, URIRef
from rdflib.namespace import RDF

yaml_file = 'library.yaml'

turtle = Graph ()
LIBRARY = Namespace ('dokk:library:')
SCHEMA  = Namespace ('http://schema.org/')
SPDX    = Namespace ('http://spdx.org/rdf/terms#')
turtle.bind ('schema', SCHEMA)
turtle.bind ('spdx', SPDX)

with open (yaml_file, 'r') as stream:
    try:
        library = yaml.load (stream)
    except yaml.YAMLError as exc:
        print (exc)

for id in library:
    turtle.add ((LIBRARY[id],
                 RDF.type,
                 URIRef (SCHEMA.CreativeWork)))
    
    turtle.add ((LIBRARY[id],
                 SCHEMA.title,
                 Literal (library[id]['title'])))
    
    turtle.add ((LIBRARY[id],
                 SCHEMA.identifier,
                 Literal (id)))
    
    if isinstance (library[id]['copyrightYear'], list):
        for year in library[id]['copyrightYear']:
            turtle.add ((LIBRARY[id],
                         SCHEMA.copyrightYear,
                         Literal (year)))
    else:
        turtle.add ((LIBRARY[id],
                     SCHEMA.copyrightYear,
                     Literal (library[id]['copyrightYear'])))
        
    if isinstance (library[id]['inLanguage'], list):
        for language in library[id]['inLanguage']:
            turtle.add ((LIBRARY[id],
                         SCHEMA.inLanguage,
                         Literal (language)))
    else:
        turtle.add ((LIBRARY[id],
                     SCHEMA.inLanguage,
                     Literal (library[id]['inLanguage'])))
        
    if isinstance (library[id]['keywords'], list):
        for keywords in library[id]['keywords']:
            turtle.add ((LIBRARY[id],
                         SCHEMA.keywords,
                         Literal (keywords)))
    else:
        turtle.add ((LIBRARY[id],
                     SCHEMA.keywords,
                     Literal (library[id]['keywords'])))
        
    if isinstance (library[id]['license'], list):
        for license in library[id]['license']:
            turtle.add ((LIBRARY[id],
                         SCHEMA.license,
                         URIRef (SPDX[license])))
    else:
        turtle.add ((LIBRARY[id],
                     SCHEMA.license,
                     URIRef (SPDX[library[id]['license']])))

turtle.serialize ('library.ttl', 'turtle')
