# zetup.py
#
# Zimmermann's Python package setup.
#
# Copyright (C) 2014 Stefan Zimmermann <zimmermann.code@gmail.com>
#
# zetup.py 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.
#
# zetup.py 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 zetup.py. If not, see <http://www.gnu.org/licenses/>.

import os
from textwrap import dedent

from path import path as Path

from jinja2 import FileSystemLoader, TemplateNotFound
from jinjatools import Environment

from zetup import Zetup
from zetup.commands import ZetupCommandError


class Loader(FileSystemLoader):
    def __init__(self):
        self.templates_dir = Path(__path__[0]) / 'templates'
        super(Loader, self).__init__(self.templates_dir)

    def get_source(self, env, target):
        source, _, uptodate = super(Loader, self).get_source(
          env, target + '.jinja')
        return source, target, uptodate


class Made(list):
    def __init__(self):
        self.status = 0

    def clean(self):
        for path in self:
            path.remove()

    def __enter__(self):
        return self

    def __exit__(self, *exc_info):
        self.clean()


class ZetupMakeError(ZetupCommandError):
    def __init__(self, made, message):
        ZetupCommandError.__init__(self, message)
        made.clean()


@Zetup.command()
def make(self, args=None, targets=None, force=False, skip_existing=False):
    if args:
        targets = args.targets
        force = args.force
    if not targets:
        raise ZetupCommandError("No targets given. You can 'make all'.")
    env = Environment(loader=Loader())
    if 'all' in targets:
        targets = [tname.rsplit('.', 1)[0]
                   for tname in os.listdir(env.loader.templates_dir)
                   if tname.endswith('.jinja')]
        skip_existing = True

    made = Made()
    for target in targets:
        path = Path(self.ZETUP_DIR) / target
        if path.exists():
            if skip_existing:
                continue
            if not force:
                raise ZetupMakeError(made,
                  "Target '%s' already exists." % target
                  + "Overwrite with -f or --force")
        try:
            template = env.get_template(target)
        except TemplateNotFound:
            raise ZetupMakeError(made,
              "No template for target '%s'." % target)
        text = template.render({
          'zetup_header': dedent("""
            # This file was auto-generated by zetup
            #
            # https://bitbucket.org/userzimmermann/zetup.py
            """),
          'zfg': self,
          })
        path.write_text(text.strip())
        made.append(path)

    return made
