# Copyright 2014 MongoDB, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""
A function that creates tasks that migrate ``.po`` files generated by Sphinx's
``gettext`` builder to the ``locale`` directory in the source directory to use
as a basis for translation.
"""

import os.path
import logging

import libgiza.task

from giza.tools.files import expand_tree, copy_if_needed
from giza.config.sphinx_config import resolve_builder_path

logger = logging.getLogger('giza.content.post.gettext')

# Gettext Processing


def gettext_tasks(conf):
    locale_dirs = os.path.join(conf.paths.projectroot,
                               conf.paths.locale, 'pot')

    builder_name = resolve_builder_path('gettext', conf.project.edition, None, conf)

    branch_output = os.path.join(conf.paths.projectroot,
                                 conf.paths.branch_output,
                                 builder_name)

    path_offset = len(branch_output) + 1

    tasks = []
    for fn in expand_tree(branch_output, None):
        target = os.path.join(locale_dirs, fn[path_offset:])
        source = fn

        t = libgiza.task.Task(job=copy_if_needed,
                              args=(source, target, None),
                              target=target,
                              dependency=source,
                              description="migrating po file {0} if needed".format(fn))
        tasks.append(t)

    logger.info("if you added files to the corpus since your last gettext build,"
                "please run the gettext build a second time for complete finalization.")

    return tasks
