#! /usr/bin/env python
from __future__ import print_function
import os
from abjad.tools import systemtools


def find_local_import_statements():
    total_local_import_statements = 0
    for path, subdirectories, files in os.walk('.'):
        if '.svn' not in path and 'docs' not in path:
            for f in files:
                if f.endswith('.py') and not f == '__init__.py':
                    full_file_name = os.path.join(path, f)
                    result = find_local_import_statements_in_file(
                        full_file_name)
                    total_local_import_statements += result

    total = total_local_import_statements
    print('Total local import statements: {}'.format(total))
    print()


def find_local_import_statements_in_file(full_file_name):
    total_local_import_statements = 0
    file_parts = full_file_name.split(os.path.sep)
    module = file_parts[-2]
    function = file_parts[-1]
    shorter_module_name = '{}{}{}'.format(module, os.path.sep, function)
    with open(full_file_name, 'r') as file_pointer:
        for line in file_pointer:
            if line.startswith('from') and \
                not line.startswith('from experimental import *') and \
                not line.startswith(
                    'from make_illustration_from_output_material') and \
                not line.startswith('from _'):
                line_parts = line.split()
                module_name = line_parts[1]
                if module_name not in ('abjad', '__future__'):
                    if '.' not in module_name:
                        if total_local_import_statements == 0:
                            print(shorter_module_name)
                            total_local_import_statements += 1
                        print(line.strip())
    if 0 < total_local_import_statements:
        print()
    return total_local_import_statements


if __name__ == '__main__':
    systemtools.IOManager.clear_terminal()
    find_local_import_statements()
