#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
Synopsis:
    Split the output module generated by generateDS.py into separate modules,
    one for each data representation class.
Usage:
    python split_gds_classes.py [options]
Options:
    -h, --help      Display this help message.
    -p, --path      Target output directory.
    -q, --quiet     Quiet -- Do not print messages.
Example:
    python split_gds_classes.py -p output_directory generated_module.py
"""

#
# Imports

import sys
import os
import getopt
import re

#
# Globals and constants
Rep_classes_start = "# Data representation classes."
Class_name_pattern1 = re.compile(r'class (\w*)\((\w*)\):')
Class_name_pattern2 = re.compile(r'class (\w*):')

Pre_template = '''\
from header_mod import *

'''

Post_template = '''\
'''


#
# Functions for external use


def strip_classes(in_file_name, path, quiet):
    in_file = open(in_file_name, 'r')
    line = in_file.next()
    while line.find(Rep_classes_start) == -1:
        line = in_file.next()
    # Find the first data representation class.
    while not line.startswith('class '):
        line = in_file.next()
    # Extract each data representation class.
    while not line.startswith('USAGE_TEXT'):
        match_obj = Class_name_pattern1.match(line)
        superclass_name = None
        if match_obj is not None:
            class_name = match_obj.group(1)
            superclass_name = match_obj.group(2)
        else:
            match_obj = Class_name_pattern2.match(line)
            if match_obj is not None:
                class_name = match_obj.group(1)
        path_name = os.path.join(path, '%s_mod.py' % class_name)
        if not quiet:
            print 'Generating: %s' % (path_name, )
        out_file = open(path_name, 'w')
        out_file.write(Pre_template)
        if (superclass_name is not None and
                superclass_name != 'GeneratedsSuper'
                ):
            import_line = 'from %s_mod import %s\n\n' % (
                    superclass_name, superclass_name, )
            out_file.write(import_line)
        out_file.write(line)
        line = in_file.next()
        while (
                (not line.startswith('class ')) and
                (not line.startswith('USAGE_TEXT'))
            ):
            out_file.write(line)
            line = in_file.next()
        out_file.write(Post_template)
        out_file.close()


USAGE_TEXT = __doc__


def usage():
    print USAGE_TEXT
    sys.exit(1)


def main():
    args = sys.argv[1:]
    try:
        opts, args = getopt.getopt(args, 'hp:q', ['help', 'path=', 'quiet', ])
    except:
        usage()
    path = ''
    quiet = False
    for opt, val in opts:
        if opt in ('-h', '--help'):
            usage()
        elif opt in ('-p', '--path'):
            path = val
        elif opt in ('-q', '--quiet'):
            quiet = True
    if len(args) != 1:
        usage()
    in_file_name = args[0]
    strip_classes(in_file_name, path, quiet)


if __name__ == '__main__':
    #import pdb; pdb.set_trace()
    main()
