#!C:\Python27\python.exe

# Copyright 2011-2013, Sonal Raj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

""" Geoff command line tool
"""

from __future__ import print_function

import argparse
import sys

from neopy import neo4j, geoff


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Pass Geoff data to a Neo4j database server for insert, merge or delete.")
    parser.add_argument("-H", "--host", metavar="host", default='localhost', help="Neo4j server host name")
    parser.add_argument("-P", "--port", metavar="port", default=7474, help="Neo4j server port")
    parser.add_argument("-D", "--database-path", metavar="path", default='/db/data/', help="path of graph database (e.g. /db/data/)")
    parser.add_argument("operation", help="Geoff operation (insert|merge)")
    parser.add_argument("file", nargs="?", default="-", help="file from which to load Geoff data")
    args = parser.parse_args()
    graph_db = neo4j.GraphDatabaseService("http://{host}:{port}{path}".format(host=args.host, port=args.port, path=args.database_path))
    if args.file == "-":
        file = sys.stdin
    else:
        file = open(args.file)
    if args.operation == "insert":
        params = geoff.Subgraph.load(file).insert_into(graph_db)
    elif args.operation == "merge":
        params = geoff.Subgraph.load(file).merge_into(graph_db)
    elif args.operation == "insert-xml":
        params = geoff.Subgraph.load_xml(file).insert_into(graph_db)
    elif args.operation == "merge-xml":
        params = geoff.Subgraph.load_xml(file).merge_into(graph_db)
    else:
        sys.stderr.write("Unknown operation: " + args.operation + "\n")
        sys.exit(1)
    for key, value in params.items():
        sys.stdout.write(key)
        sys.stdout.write("\t")
        sys.stdout.write(str(value))
        sys.stdout.write("\n")
