"""A module that generates vcal_dict.py.

vcal_dict.py contains a dict of tuples (tzid, vcal_representation)
indexed by their pytz id.

To generate the file when new version of Olson database appears follow
these steps:

1. Download vzic source code from:

  http://dspace.dial.pipex.com/prod/dialspace/town/pipexdsl/s/asbm26/vzic/

2. Apply vzic.patch to it (the patch was created for version 1.2 of
   vzic).

3. Follow the instructions in vzic README file to generate a set of
   ics files.

4. Run this script passing the name of the generated zoneinfo
   directory as the first and only parameter.

"""
import os
import sys
import pytz
from textwrap import dedent


def extract_tzlocation(path, file):
    """Determine the id of the timezone."""
    assert file.startswith(path + os.path.sep)
    assert file.lower().endswith('.ics')
    return file[len(path)+1:-4].replace(os.path.sep, '/')


def walk_ics(path):
    """Generator yielding tuples of timezone data for all ics files in the path.

    Returns tuples containing (tzlocation, tzid, vcalendar) where:
      tzlocation is the pytz timezone id.
      tzid is the VCALENDAR timezone id.
      vcalendar is a string containing the VCALENDAR represantation of
      the timezone.

    """
    path = os.path.abspath(path)
    for dir, subdirs, files in os.walk(path):
        for file in files:
            if file.endswith(".ics"):
                tzlocation = extract_tzlocation(path, os.path.join(dir, file))
                if tzlocation in pytz.all_timezones:
                    pytz_tz = pytz.timezone(tzlocation)
                    ics_file = open(os.path.join(dir, file))
                    lines = ics_file.read().splitlines()
                    vcalendar = "\n".join(lines[3:-1])
                    tzid = lines[4].split(":")[1]
                    yield tzlocation, tzid, vcalendar
                else:
                    print "Timezone %r was not found" % tzlocation


def main(argv):
    if len(argv) < 2:
        print __doc__
        sys.exit(1)

    vcdict = open("vcal_dict.py", "w")
    print >> vcdict, dedent("""\
    #
    # This file was generated by generate_vcal_dict.py, DO NOT EDIT!
    # Instructions on updating this file can be found in generate_vcal_dict.py.
    #
    """)
    print >> vcdict, "timezone_map = {"
    for tzlocation, tzid, vcalendar in walk_ics(argv[1]):
        print >> vcdict, "%r : (%r, '''%s''')," % (tzlocation, tzid, vcalendar)
    print >> vcdict, "}"


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