import os.path
import pkg_resources


class Requirements(object):
    """Generate a pip compatible requirements.txt from our working set based on
    the 'batou' requirement."""

    def __init__(self, buildout, name, options):
        self.name, self.options = name, options
        options['path'] = os.path.join(
            buildout['buildout']['directory'], 'src', 'batou')

    def install(self):
        path = self.options['path'] + '/requirements.txt'
        require = pkg_resources.Requirement.parse('batou')
        dependencies = pkg_resources.working_set.resolve([require])
        seen = set(['batou'])
        with open(path, 'w') as requirements_txt:
            requirements_txt.write('# Generated by buildout\n')
            for dep in reversed(dependencies):
                dep = dep.as_requirement()
                if dep.key in seen:
                    continue
                seen.add(dep.key)
                requirements_txt.write(str(dep) + '\n')
        with open(self.options['path'] + '/version.txt', 'w') as f:
            f.write('{}\n'.format(pkg_resources.require('batou')[0].version))
        return []

    update = install
