#! /usr/bin/env python

import sys
import os
import glob
from fontTools.ttLib import identifierToTag
import textwrap


fontToolsDir = os.path.dirname(os.path.dirname(os.path.join(os.getcwd(), sys.argv[0])))
fontToolsDir= os.path.normpath(fontToolsDir)
tablesDir = os.path.join(fontToolsDir,
		"Lib", "fontTools", "ttLib", "tables")
docFile = os.path.join(fontToolsDir, "README.rst")

names = glob.glob1(tablesDir, "*.py")

modules = []
tables = []
for name in names:
	try:
		tag = identifierToTag(name[:-3])
	except:
		pass
	else:
		modules.append(name[:-3])
		tables.append(tag.strip())

modules.sort()
tables.sort()


with open(os.path.join(tablesDir, "__init__.py"), "w") as file:

	file.write('''
from __future__ import print_function, division, absolute_import
from fontTools.misc.py23 import *

# DON'T EDIT! This file is generated by MetaTools/buildTableList.py.
def _moduleFinderHint():
	"""Dummy function to let modulefinder know what tables may be
	dynamically imported. Generated by MetaTools/buildTableList.py.

		>>> _moduleFinderHint()
	"""
''')

	for module in modules:
		file.write("\tfrom . import %s\n" % module)

	file.write('''
if __name__ == "__main__":
	import doctest, sys
	sys.exit(doctest.testmod().failed)
''')


begin = ".. begin table list\n.. code::\n"
end = ".. end table list"
with open(docFile) as f:
	doc = f.read()
beginPos = doc.find(begin)
assert beginPos > 0
beginPos = beginPos + len(begin) + 1
endPos = doc.find(end)

lines = textwrap.wrap(", ".join(tables[:-1]) + " and " + tables[-1], 66)
blockquote = "\n".join(" "*4 + line for line in lines) + "\n"

doc = doc[:beginPos] + blockquote + doc[endPos:]

with open(docFile, "w") as f:
	f.write(doc)