# Copyright 2016 Google Inc. All Rights Reserved.
#
# 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.

"""Tasks related to generation of GAPIC wrappers"""

import os

from artman.tasks import task_base
from artman.utils import task_utils
from artman.utils.logger import logger


class StagingOutputDirTask(task_base.TaskBase):
    """Output the code gen dir as staging_code_dir
    """
    default_provides = ['staging_code_dir', 'staging_lang_api_dir']

    def execute(self, language, api_name, api_version, organization_name,
                gapic_code_dir, staging_repo_dir):
        api_full_name = task_utils.api_full_name(
            api_name, api_version, organization_name)
        return [gapic_code_dir,
                os.path.join(staging_repo_dir, language, api_full_name)]


class StagingGrpcOutputDirTask(task_base.TaskBase):
    """Output the code gen dir as staging_code_dir
    """
    default_provides = ['staging_code_dir', 'staging_lang_api_dir']

    def execute(self, language, api_name, api_version, organization_name,
                package_dir, staging_repo_dir):
        api_full_name = task_utils.api_full_name(
            api_name, api_version, organization_name)
        staging_lang_api_dir = os.path.join(
            staging_repo_dir, language, 'grpc-' + api_full_name)
        return [package_dir, staging_lang_api_dir]


class StagingCleanTask(task_base.TaskBase):
    """Delete all of the files in the staging_lang_api_dir.
    """

    def execute(self, staging_lang_api_dir):
        self.exec_command(['rm', '-rf', staging_lang_api_dir])


class StagingCopyTask(task_base.TaskBase):
    """Copy the files generated by Gapic toolkit to the staging_lang_api_dir
    """

    def execute(self, language, staging_lang_api_dir, staging_code_dir):
        logger.info('Copying %s/* to %s.' %
                    (staging_code_dir, staging_lang_api_dir))
        self.exec_command(['mkdir', '-p', staging_lang_api_dir])
        for entry in os.listdir(staging_code_dir):
            src_path = os.path.join(staging_code_dir, entry)
            self.exec_command([
                'cp', '-rf', src_path, staging_lang_api_dir])
