# This script generates the mapping between MS Windows timezone names and
# tzdata/Olsen timezone names, by retrieving a file:
# http://unicode.org/cldr/data/common/supplemental/supplementalData.xml
# and parsing it, and from this generating the file windows_tz.py.
#
# It must be run with Python 3.

XML_SOURCE = 'http://unicode.org/cldr/data/common/supplemental/windowsZones.xml'
from urllib.request import urlopen
from xml.dom import minidom
from pprint import pprint

source = urlopen(XML_SOURCE).read()
dom = minidom.parseString(source)

for element in dom.getElementsByTagName('mapTimezones'):
    if element.getAttribute('type') == 'windows':
        break

win_tz = {}
tz_win = {}
for mapping in element.getElementsByTagName('mapZone'):
    if mapping.getAttribute('territory') == '001':
        win_tz[mapping.getAttribute('other')] = mapping.getAttribute('type').split(' ')[0]

    for tz_name in mapping.getAttribute('type').split(' '):
        tz_win[tz_name] = mapping.getAttribute('other')

# Etc/UTC is a common alias for Etc/GMT:
tz_win['Etc/UTC'] = 'UTC'

with open('tzlocal/windows_tz.py', "wt") as out:
    out.write("# This file is autogenerated by the get_windows_info.py script\n"
              "# Do not edit.\nwin_tz = ")
    pprint(win_tz, out)
    out.write("\n# Old name for the win_tz variable:\ntz_names = win_tz\n\ntz_win = ")
    pprint(tz_win, out)
