#!/usr/bin/env python

#############################################################################
##
## This file is part of Taurus, a Tango User Interface Library
## 
## http://www.tango-controls.org/static/taurus/latest/doc/html/index.html
##
## Copyright 2011 CELLS / ALBA Synchrotron, Bellaterra, Spain
## 
## Taurus is free software: you can redistribute it and/or modify
## it under the terms of the GNU Lesser General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
## 
## Taurus is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU Lesser General Public License for more details.
## 
## You should have received a copy of the GNU Lesser General Public License
## along with Taurus.  If not, see <http://www.gnu.org/licenses/>.
##
#############################################################################

"""
This script is designed to provide taurus developers with a fast way to test
sphinx documentation from source code files or RST files.
"""

import sys
import os
import shutil
import optparse

from sphinx.application import Sphinx
from sphinx.util.console import darkred, nocolor, color_terminal

import taurus.core

def abspath(*path):
    """A method to determine absolute path for a given relative path to the
    directory where this script is located"""
    taurusdoc_dir = os.path.dirname(os.path.abspath(__file__))
    return os.path.join(taurusdoc_dir, *path)

sys.path.append(abspath('..', 'doc'))

try:
    import auto_rst4api
except ImportError:
    print "taurusdoc can only be executed from a source distribution of taurus"
    sys.exit(1)

__INDEX = """
TaurusDoc
---------

This document has been autogenerated by taurusdoc for test purposes.
Any modifications will be lost.
  
.. toctree::
    
    {name}
"""

class RstCreator(auto_rst4api.Auto_rst4API_Creator):
    
    def documentClass(self, module, classname, docparentpath):
        '''Documents a single class
        
        :param module: (module) python module where class resides
        :param classname: (str) class name
        :docparentpath: (str) path to the directory in which the documentation 
                        files will be written
        '''
        ofname = os.path.join(docparentpath,"_%s.rst"%classname)

        if self.verbose: print 'creating "%s" ...' % ofname,
        info = dict(modulename = module.__name__,
                    basemodulename = module.__name__.split('.')[-1],
                    modulepath = module.__path__,
                    submodulenames = [], 
                    localclassnames = [classname],
                    localfunctionnames = [],
                    localenumerationnames = [],
                    externalmembernames = [],
                    submodules = [],
                    warnings = [])
        if not os.path.exists(ofname) or self.overwrite_old:
            text = self.classtemplate.render(info=info, classname=classname)
            f = open(ofname, "w")
            f.write('\n'.join((self.AUTOGEN_SIGNATURE, self.AUTOGEN_MESSAGE, text)))
            f.close()
            if self.verbose: print ' ok.'
        else:
            if self.verbose: print ' skipping (file already exists)'
        

def main():
    version = "taurusdoc %s" % (taurus.Release.version)
    usage = "usage: %prog [options]"
    description = "a tool to help developers preview the documentation "\
                  "generated by their code"
    parser = optparse.OptionParser(usage=usage, version=version, description=description)
    
    parser.add_option("-v", "--verbose", dest="verbose", action="store_true",
                      help="display a lot of information [default]", default=True)
    parser.add_option("-q", "--quiet", dest="verbose", action="store_false",
                      help="be really silent")
    parser.add_option("--build-dir", dest="build_dir",
                      help="build directory [default=./build]")
    parser.add_option("-a", "--all-files", dest="all_files", default=True, action="store_true",
                      help="generate from scratch [default]")
    parser.add_option("--cache", dest="all_files", action="store_false",
                      help="use previously generated files")

    #o_group = optparse.OptionGroup(parser, "output options",
    #                             "options regarding the ouput")
    
    parser.add_option("--format", dest="builder", default="html",
                      help="output format [default=html]")

    parser.add_option("--prefix", dest="prefix",
                      help="output directory")

    #i_group = optparse.OptionGroup(parser, "input options",
    #                               "provide one and **only** one  of these!")
                      
    parser.add_option("--class", dest="klass", default=None,
                      help="full class name to generate doc for (ex.: taurus.qt.qtgui.display.TaurusLabel")
    parser.add_option("--package", dest="package", default=None,
                      help="full package name to generate doc for (ex.: taurus.qt.qtgui.display)")
    parser.add_option("--file", dest="filename", default=None,
                      help="RST file")

    options, args = parser.parse_args()

    if not options.klass and not options.package and not options.filename:
        parser.error("must give one of --class or --package or --file")
    
    if int(bool(options.klass)) + int(bool(options.package)) + int(bool(options.filename)) > 1:
        parser.error("options --class and --package and --file are mutually exclusive")

    fromlist = []
    
    if options.klass:
        package_name, class_name = options.klass.rsplit(".", 1)
        if package_name.find(".") >= 0:
            fromlist.append( package_name.split(".", 1)[0] )
        mod = __import__(package_name, fromlist=fromlist)
    elif options.package:
        package_name = options.package
        mod = __import__(package_name, fromlist=fromlist)
    else:
        filename = options.filename
    
    if options.build_dir is None:
        options.build_dir = os.path.join(os.path.abspath(os.path.curdir), "build")

    # clean build dir
    if options.all_files:
        if os.path.isdir(options.build_dir):
            shutil.rmtree(options.build_dir)
    
    if not os.path.isdir(options.build_dir):
        os.makedirs(options.build_dir)
    
    if options.prefix is None:
        options.prefix = os.path.join(os.path.abspath(os.path.curdir), "sphinx")

    if not os.path.isdir(options.prefix):
        os.makedirs(options.prefix)
    
    doc_dir = abspath("..", "doc")

    if options.verbose:
        out = sys.stdout
    else:
        import StringIO
        out = StringIO.StringIO()

    if not options.filename:
        rstCreator = RstCreator(exclude_patterns=['.*\.ui'], templatespath=doc_dir,
                                overwrite_old=True, verbose=options.verbose,
                                classtemplate='api_class_simple.rst')

        rstCreator.cleanAutogenerated(options.build_dir)

    # create index.rst
    index_rst = os.path.join(options.build_dir, 'index.rst')
    f = file(index_rst, "w")
    if options.klass:
        r = rstCreator.documentClass(mod, class_name, options.build_dir)
        txt = __INDEX.format(name="_%s" % class_name)
    elif options.package:
        r = rstCreator.documentModule(package_name, options.build_dir)
        txt = __INDEX.format(name=package_name.rsplit(".", 1)[-1])
    else:
        shutil.copy(options.filename, options.build_dir)
        txt = __INDEX.format(name=os.path.basename(options.filename))
    f.write(txt)
    f.close()

    # directory where conf.py resides
    config_dir = os.path.join(doc_dir, 'source')
    doctree_dir = os.path.join(options.build_dir, 'doctrees')

    app = Sphinx(options.build_dir, config_dir, options.prefix,
                 doctree_dir, options.builder,
                 confoverrides=None, status=out, warning=sys.stderr,
                 freshenv=False, warningiserror=False, tags=None)

    app.build()
    
if __name__ == "__main__":
    main()