#!/usr/bin/python
# coding=utf-8

# this, combined with tf_realtime is extremely un-dry!

import sys
import optparse
import trafikanten
import trafikanten.util as util
import os

FMT_XML = 1
FMT_CSV = 2
FMT_TAB = 3
FMT_CUSTOM = 4
FMT_HUMAN = 5

def parse_options():
    usage = """%prog station_id [options]

Searches for stops by search term. By default the information is written to
stdout in human readable form"""
    parser = optparse.OptionParser(usage)

    parser.add_option("-f", "--file", dest="filename",
                      help="write output to FILE", metavar="FILE")
    parser.add_option("-o", "--overwrite", dest="overwrite",
                      default=False, action="store_true",
                      help="overwrite output file if it exists")
    parser.add_option("-x", "--xml", dest="format", action="store_const",
                      const=FMT_XML, help="write output in xml format")
    parser.add_option("-c", "--csv", dest="format", action="store_const",
                      const=FMT_CSV, help="write output in csv format")
    parser.add_option("-t", "--tab", dest="format", action="store_const",
                      const=FMT_TAB, help="write output as tab separated data")
    parser.add_option("-s", "--separator",
                      help="write output separatted by SEPARATOR",
                      metavar="SEPARATOR", dest="separator",
                      default=None)
    parser.add_option("-n", "--names", action="store_true", dest="names",
                      default=False, help="include header with row names (only with custom separator)" )
    parser.add_option("-d", "--district", help="show only hits for DISTRICT",
                      metavar="DISTRICT", dest="district", default=None)

    options, args = parser.parse_args()

    if options.filename and not options.overwrite \
                and os.path.isfile(options.filename):
        parser.error("""File "%s" allready exists. Use -o to overwrite""" % options.filename)

    if len(args) != 1:
        parser.error("Wrong number of arguments: Takes one argument, the search term")

    if not options.format:
        if options.separator:
            options.format = FMT_CUSTOM
        else:
            options.format = FMT_HUMAN

    if options.district:
        optparse.district = options.district.lower()

    return options, args[0]

def main():
    """Main application entry point"""
    options, sid = parse_options()
    if options.filename:
        # we're not using codecs.open because then we need to keep track of
        # if we're using a wrapped file or not. All output will be done
        # in utf-8 explicitly when we call .write
        outfile = open(options.filename, "wb")
    else:
        outfile = sys.stdout

    res = trafikanten.find_station(sid)

    if options.district:
        res = [e for e in res if e["district"].lower() == options.district]

    if options.format == FMT_HUMAN:
        data = util.make_human_readable_stations(res)
    elif options.format == FMT_XML:
        data = util.make_xml_stations(res)
    else:
        if options.format == FMT_CSV:
            sep = ";"
        elif options.format == FMT_TAB:
            sep = "\t"
        elif options.format == FMT_CUSTOM:
            sep = options.separator

        data = util.make_delimited_stations(res, separator=sep, header=options.names)

    data = data + u"\n"
    enc = outfile.encoding or "utf-8"
    outfile.write(data.encode(enc, "replace"))

if __name__ == "__main__":
    sys.exit(main())
