from py2neo import authenticate, Graph, Node, Relationship

import sys, getopt, os, datetime
import csv, codecs, cStringIO

from py2neo.packages.httpstream import http

http.socket_timeout = 9999


# This is from http://stackoverflow.com/questions/5838605/python-dictwriter-writing-utf-8-encoded-csv-files :-)
class DictUnicodeWriter(object):
    def __init__(self, f, fieldnames, dialect=csv.excel, encoding="utf-8", **kwds):
        # Redirect output to a queue
        self.queue = cStringIO.StringIO()
        self.writer = csv.DictWriter(self.queue, fieldnames, dialect=dialect, **kwds)
        self.stream = f
        self.encoder = codecs.getincrementalencoder(encoding)()

    def writerow(self, D):
        self.writer.writerow(dict((k, v.encode('utf-8') if isinstance(v, unicode) else v) for k, v in D.iteritems()))
        # Fetch UTF-8 output from the queue ...
        data = self.queue.getvalue()
        data = data.decode("utf-8")
        # ... and reencode it into the target encoding
        data = self.encoder.encode(data)
        # write to the target stream
        self.stream.write(data)
        # empty queue
        self.queue.truncate(0)

    def writerows(self, rows):
        for D in rows:
            self.writerow(D)

    def writeheader(self):
        self.writer.writeheader()


class table(object):
    def __init__(self):
        self.columnHeadings = []
        self.rows = []

    def addRow(self, row):
        for col_name in row:
            if col_name not in self.columnHeadings:
                self.columnHeadings.append(col_name)  # accumulate column headings for later output
        self.rows.append(row)

    def saveCsv(self, path, filename):
        fieldnames = [s.encode("utf-8") for s in self.columnHeadings]
        fieldnames.sort()
        fullpath = os.path.join(path, filename)
        with open(fullpath, 'wb') as csvfile:
            print "\tWriting to", fullpath
            csvfile.write(u'\ufeff'.encode('utf8'))  # BOM (optional...Excel needs it to open UTF-8 file properly)
            csvwriter = DictUnicodeWriter(csvfile, fieldnames)
            csvwriter.writeheader()
            csvwriter.writerows(self.rows)


def usage():
    print "Usage", sys.argv[0]
    print " -? | --help {show this help}"
    print " protocol=[http|https] {default=http}"
    print " host=[neo4j hostname] {default=localhost"
    print " port=[neo4j port number] {default=7474}"
    print " db=[relative path to neo4j db] {default=/db/data"
    print " userid=[neo4j user id {default=none}"
    print " password=[passsword] {default=none}"
    print " limit=[number: limit rows returned, 0 for all] {default=0}"
    print " csvpath=[path to folder where CSV files are written] {default=.}"
    print " nodelabels=[comma delimited list of node labels, get list from db if empty] {default=}"