import rdflib
import argparse

SYNTAXES = ["xml", "n3", "nt", "ttl"]

HTACCESS_TEMPLATE = """
RewriteEngine on
RewriteBase /

AddType application/rdf+xml .rdf
AddType text/turtle .ttl

# Rewrite rule to serve HTML content from the vocabulary URI if requested
RewriteCond %{REQUEST_URI} "/voc/FILE"
RewriteCond %{HTTP_ACCEPT} "text/html"
RewriteRule ^voc/FILE/?$ voc/FILE/FILE.html [R=303,L]

# Rewrite rule to serve RDF/XML content from the vocabulary URI if requested
RewriteCond %{REQUEST_URI} "/voc/FILE"
RewriteCond %{HTTP_ACCEPT} "application/rdf\+xml"
RewriteRule ^voc/FILE/?$ voc/FILE/FILE.rdf [R=303,L]

# Rewrite rule to serve RDF/XML content from the vocabulary URI if requested
RewriteCond %{REQUEST_URI} "/voc/FILE"
RewriteCond %{HTTP_ACCEPT} "text/n3"
RewriteRule ^voc/FILE/?$ voc/FILE/FILE.n3 [R=303,L]

# Rewrite rule to serve RDF/XML content from the vocabulary URI if requested
RewriteCond %{REQUEST_URI} "/voc/FILE"
RewriteCond %{HTTP_ACCEPT} "application/n-triples"
RewriteRule ^voc/FILE/?$ voc/FILE/FILE.nt [R=303,L]

# Rewrite rule to serve TTL content from the vocabulary URI if requested
RewriteCond %{REQUEST_URI} "/voc/FILE"
RewriteCond %{HTTP_ACCEPT} "text/turtle" [OR]
# This is the default
RewriteCond %{HTTP_ACCEPT} !^$
RewriteRule ^voc/FILE/?$ voc/FILE/FILE.ttl [R=303,L]
"""

# Argument parsing
parser = argparse.ArgumentParser(description='Saves an RDF file in multiple formats.')
parser.add_argument("-i", "--input", help="Input resource (path or IRI)")
parser.add_argument("-o", "--output", help= "Output directory")
parser.add_argument("-f", "--file", help="The output file name")
args = parser.parse_args()

if args.input == None or args.output == None or args.file == None:
    print(parser.print_help())
    exit(-1)


g = rdflib.Graph()
result = g.parse(args.input)
for syntax in SYNTAXES:
    with open(args.output+"/"+args.file+"."+syntax, "w") as f:
        f.write(g.serialize(format=syntax).decode("utf-8"))
with open(args.output+"/.htaccess", "w") as f:
    f.write(HTACCESS_TEMPLATE.replace("FILE", args.file))
