import os, glob
from distutils import util
from distutils.core import Command

class InstallData(Command):

    command_name = 'install_data'

    description = "install data files"

    user_options = [
        ('force', 'f', "force installation (overwrite existing files)"),
        ]

    def initialize_options(self):
        self.install_dir = None
        self.force = None
        self.data_files = self.distribution.data_files
        return

    def finalize_options (self):
        self.set_undefined_options('install',
                                   ('install_data', 'install_dir'),
                                   ('force', 'force'),
                                  )
        return

    def run(self):
        self.mkpath(self.install_dir)
        for dot_path, globs in self.data_files:
            # Convert the package path into a directory path
            dir = dot_path.replace('.', os.sep)
            dir = os.path.join(self.install_dir, dir)
            self.mkpath(dir)

            # Convert the list of filespecs into a list of actual files
            for spec in globs:
                for file in glob.glob(util.convert_path(spec)):
                    self.copy_file(file, dir)
        return

    def get_inputs(self):
        inputs = []
        for dot_path, globs in self.data_files:
            # Convert the list of filespecs into a list of actual files
            for spec in globs:
                inputs.extend(glob.glob(util.convert_path(spec)))
        return inputs

    def get_outputs(self):
        outputs = []
        for dot_path, globs in self.data_files:
            # Convert the package path into a directory path
            dir = dot_path.replace('.', os.sep)
            dir = os.path.join(self.install_dir, dir)

            # Convert the list of filespecs into a list of actual files
            for spec in globs:
                for src in glob.glob(util.convert_path(spec)):
                    src = os.path.basename(src)
                    outputs.append(os.path.join(dir, src))
        return outputs
