#!/usr/bin/env python
# coding=utf-8
##########################################################################

from __future__ import print_function
import configobj
import optparse
import os
import shutil
import sys
import tempfile
import traceback

sys.path.append(os.path.abspath(
    os.path.join(os.path.dirname(__file__), 'src')))


def getIncludePaths(path):
    for f in os.listdir(path):
        cPath = os.path.abspath(os.path.join(path, f))

        if os.path.isfile(cPath) and len(f) > 3 and f.endswith('.py'):
            sys.path.append(os.path.dirname(cPath))

        elif os.path.isdir(cPath):
            getIncludePaths(cPath)

collectors = {}


def getCollectors(path):
    for f in os.listdir(path):
        cPath = os.path.abspath(os.path.join(path, f))

        if os.path.isfile(cPath) and len(f) > 3 and f.endswith('.py'):
            modname = f[:-3]

            if modname.startswith('Test'):
                continue
            if modname.startswith('test'):
                continue

            try:
                # Import the module
                module = __import__(modname, globals(), locals(), ['*'])

                # Find the name
                for attr in dir(module):
                    if not attr.endswith('Collector'):
                        continue

                    cls = getattr(module, attr)

                    if cls.__module__ != modname:
                        continue

                    if cls.__name__ not in collectors:
                        collectors[cls.__name__] = module
            except Exception:
                print("Failed to import module: %s. %s" % (
                    modname, traceback.format_exc()))
                collectors[modname] = False

        elif os.path.isdir(cPath):
            getCollectors(cPath)

handlers = {}


def getHandlers(path, name=None):
    for f in os.listdir(path):
        cPath = os.path.abspath(os.path.join(path, f))

        if os.path.isfile(cPath) and len(f) > 3 and f.endswith('.py'):
            modname = f[:-3]

            if name and f is not "%s.py" % name:
                break

            try:
                # Import the module
                module = __import__(modname, globals(), locals(), ['*'])

                # Find the name
                for attr in dir(module):
                    if ((not attr.endswith('Handler') or
                         attr.startswith('Handler'))):
                        continue

                    cls = getattr(module, attr)

                    if cls.__name__ not in handlers:
                        handlers[cls.__name__] = module
            except Exception:
                print("Failed to import module: %s. %s" % (
                    modname, traceback.format_exc()))
                handlers[modname] = False

        elif os.path.isdir(cPath):
            getHandlers(cPath)


def writeDocHeader(docFile):
    docFile.write("<!--")
    docFile.write("This file was generated from the python source\n")
    docFile.write("Please edit the source to make changes\n")
    docFile.write("-->\n")


def writeDocString(docFile, name, doc):
    docFile.write("%s\n" % (name))
    docFile.write("=====\n")
    if doc is None:
        print("No __doc__ string for %s!" % name)
    docFile.write("%s\n" % doc)


def writeDocOptionsHeader(docFile):
    docFile.write("#### Options\n")
    docFile.write("\n")

    docFile.write("Setting | Default | Description | Type\n")
    docFile.write("--------|---------|-------------|-----\n")


def writeDocOptions(docFile, options, default_options):
    for option in sorted(options.keys()):
        defaultOption = ''
        defaultOptionType = ''
        if option in default_options:
            defaultOptionType = default_options[option].__class__.__name__
            if isinstance(default_options[option], list):
                defaultOption = ', '.join(map(str, default_options[option]))
                defaultOption += ','
            else:
                defaultOption = str(default_options[option])

        docFile.write("%s | %s | %s | %s\n"
                      % (option,
                         defaultOption,
                         options[option].replace("\n", '<br>\n'),
                         defaultOptionType))


def writeDoc(items, type_name, doc_path):