import os
from distutils.core import Command

class InstallDocs(Command):

    command_name = 'install_docs'

    description = "install documentation"

    user_options = [
        ('install-dir=', 'd', "directory to install documentation to"),
        ('build-dir=','b', "build directory (where to install from)"),
        ('force', 'f', "force installation (overwrite existing files)"),
        ('skip-build', None, "skip the build steps"),
        ]

    boolean_options = ['force', 'skip-build']

    def initialize_options(self):
        self.install_dir = None
        self.force = None
        self.build_dir = None
        self.skip_build = None
        self.outfiles = []
        self.html_dir = None
        return

    def finalize_options(self):
        self.set_undefined_options('build', ('build_docs', 'build_dir'))
        self.set_undefined_options('build_docs', ('html_dir', 'html_dir'))
        self.set_undefined_options('install',
                                   ('install_docs', 'install_dir'),
                                   ('skip_build', 'skip_build'),
                                   ('force', 'force'),
                                   )
        return

    def get_inputs(self):
        inputs = []
        build_docs = self.get_finalized_command('build_docs')
        inputs.extend(build_docs.get_outputs())
        return inputs

    def get_outputs(self):
        return self.outfiles

    def run(self):
        if not self.skip_build:
            self.run_command('build_docs')

        if os.path.isdir(self.build_dir):
            self.mkpath(self.install_dir)
            for src_name in self.get_inputs():
                # Find the size of the build path prefix
                common_size = len(self.build_dir)
                if self.build_dir and self.build_dir[-1] != os.sep:
                    common_size = common_size + 1

                # Trim off the build directory
                base_name = src_name[common_size:]
                dst_name = os.path.join(self.install_dir, base_name)
                self.mkpath(os.path.dirname(dst_name))

                # Copy it
                self.copy_file(src_name, dst_name)
                self.outfiles.append(dst_name)
        else:
            self.warn("'%s' does not exist -- no documents to install" %
                      self.build_dir)
        return
