#!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.

""" Cypher command line tool
"""

import argparse
import sys

from neopy import neo4j, cypher


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Execute Cypher queries against a Neo4j database server and output the results.")
    parser.add_argument("-H", "--host", metavar="host", default='localhost', help="Neo4j server host name (default \"localhost\"')")
    parser.add_argument("-P", "--port", metavar="port", default=7474, help="Neo4j server port (default 7474)")
    parser.add_argument("-D", "--database-path", metavar="path", default='/db/data/', help="path of graph database (default \"/db/data/\")")
    parser.add_argument("-f", "--format", metavar="format", default='text', help="output file format (default \"text\")")
    #parser.add_argument("-n", "--no-header", metavar="no_header", default=False, help="header suppression flag")
    parser.add_argument("query", nargs="?", default='-', help="the Cypher query to execute (if omitted, will read from standard input)")
    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.query == "-":
        query = sys.stdin.read()
    else:
        query = args.query
    def report(message, exception=None, stacktrace=None):
        if exception:
            sys.stderr.write("{0}: {1}\n".format(exception, message))
        else:
            sys.stderr.write("{0}\n".format(message))
    cypher.write(args.format, sys.stdout, graph_db, query, error_handler=report)
