#!/usr/bin/python

from os import listdir, path, makedirs
from os.path import isfile, join, exists
import pprint as pp

HERE = path.abspath(path.dirname(__file__))

MODULES_PATH = '%s/../pyeapi/' % HERE
AUTOGEN = '.. This file has been autogenerated by generate_modules.py\n\n'


def get_module_names(p):
    '''Accepts a path to search for modules. The method will filter on files
    that end in .pyc or files that start with __.

    Arguments:
        p (string): The path to search
    Returns:
        list of file names
    '''
    mods = list()
    mods = [f.split('.')[0] for f in listdir(p)
            if isfile(join(p, f)) and not f.endswith('.pyc') and not f.startswith('__')]
    print len(mods)
    return mods

def process_modules(modules):
    '''Accepts dictionary of 'client' and 'api' modules and creates
    the corresponding files.
    '''
    for mod in modules['client']:
        directory = '%s/client_modules' % HERE
        if not exists(directory):
            makedirs(directory)
        write_module_file(mod, directory, 'pyeapi')

    for mod in modules['api']:
        directory = '%s/api_modules' % HERE
        if not exists(directory):
            makedirs(directory)
        write_module_file(mod, directory, 'pyeapi.api')

    create_index(modules)

def create_index(modules):
    '''This takes a dict of modules and created the RST index file.'''
    for key in modules.keys():
        file_path = join(HERE, '%s_modules/_list_of_modules.rst' % key)
        list_file = open(file_path, 'w')

        # Write the generic header
        list_file.write('%s\n' % AUTOGEN)
        list_file.write('%s\n' % key.title())
        list_file.write('=' * len(key))
        list_file.write('\n\n')
        list_file.write('.. toctree::\n')
        list_file.write('   :maxdepth: 2\n\n')

        for module in modules[key]:
            list_file.write('   %s\n' % module)


def write_module_file(name, path, package):
    '''Creates an RST file for the module name passed in. It places it in the
    path defined
    '''
    file_path = join(path, '%s.rst' % name)
    mod_file = open(file_path, 'w')

    mod_file.write('%s\n' % AUTOGEN)
    mod_file.write('%s\n' % name.title())
    mod_file.write('=' * len(name))
    mod_file.write('\n\n')
    mod_file.write('.. toctree::\n')
    mod_file.write('   :maxdepth: 1\n\n')
    mod_file.write('.. automodule:: %s.%s\n' % (package, name))
    mod_file.write('   :members:\n')
    mod_file.write('   :undoc-members:\n')
    mod_file.write('   :show-inheritance:\n')

def main():
    modules = dict(client=None, api=None)
    modules['client'] = get_module_names(MODULES_PATH)
    modules['api'] = get_module_names('%s/api' % MODULES_PATH)
    modules['client'].sort()
    modules['api'].sort()
    process_modules(modules)






if __name__ == '__main__':
    main()
