# -*- coding: UTF-8 -*-
import sys
from sl2gtfs.mapper import make_mapping

__author__ = 'johan'

# From Bottle.
try:
    _stdout, _stderr = sys.stdout.write, sys.stderr.write
except IOError:
    _stdout = lambda x: sys.stdout.write(x)
    _stderr = lambda x: sys.stderr.write(x)


def create(sl_site_data_url, sl_gtfs_agency_stop_url):
    return make_mapping(sl_site_data_url, sl_gtfs_agency_stop_url)


def _create_csv(mapping):
    _stdout('site_id,stop_id\n')
    for site_id, stop_id in mapping:
        _stdout('{site_id},{stop_id}\n'.format(site_id=site_id, stop_id=stop_id))


def _make_python_gtfs_2_sl(mapping):
    _stdout('#!/usr/bin/env python\n')
    _stdout('# -*- coding: UTF-8 -*-\n\n')
    _stdout('# Autogenerated by sl2gtfs.py\n\n')
    _stdout("gtfs_to_sl = {\n")

    grouped = dict()
    for site_id, stop_id in mapping:
        if stop_id not in grouped:
            grouped[stop_id] = []
        grouped[stop_id].append(site_id)

    for stop_id in grouped:
        site_ids = ', '.join([site_id for site_id in grouped[stop_id]])
        _stdout("    {0}: [{1}],\n".format(stop_id, site_ids))
    _stdout("}")


def main():
    from optparse import OptionParser
    _cmd_parser = OptionParser(usage="usage: %prog [options]")
    _opt = _cmd_parser.add_option
    _opt("-s", "--sl-site-url", action="store", help="Url for SL sites.", dest="sl_site_url")
    _opt("-g", "--gtfs-stops-url", action="store", help="Url for GTFS SL mapping.", dest="gtfs_stops_url")
    _opt("--pygtfs2sl", action="store_true", help="Create a python gtfs2sl map.")
    _cmd_options, _cmd_args = _cmd_parser.parse_args()

    opt, args, parser = _cmd_options, _cmd_args, _cmd_parser

    sys.path.insert(0, '.')
    sys.modules.setdefault('sl2gtfs', sys.modules['__main__'])

    if opt.sl_site_url and opt.gtfs_stops_url:
        mapping = create(sl_site_data_url=opt.sl_site_url, sl_gtfs_agency_stop_url=opt.gtfs_stops_url)
        if opt.pygtfs2sl:
            _make_python_gtfs_2_sl(mapping=mapping)
        else:
            _create_csv(mapping=mapping)
        sys.exit(0)
    else:
        parser.print_help()
        sys.exit(1)


if __name__ == '__main__':
    main()