# -*- coding: utf-8 -*-

# Copyright 2015-2016 Mir Calculate. http://www.calculate-linux.org
#
#  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.

import sys
from calculate.core.server.func import Action, Tasks
from calculate.lib.cl_lang import setLocalTranslate, getLazyLocalTranslate
from calculate.lib.cl_template import TemplatesError
from calculate.lib.utils.files import FilesError
from calculate.update.update import UpdateError
from ..datavars import BuilderError
from calculate.lib.utils.git import GitError
from calculate.install.distr import DistributiveError

_ = lambda x: x
setLocalTranslate('cl_builder3', sys.modules[__name__])
__ = getLazyLocalTranslate(_)


class ClBuilderProfileAction(Action):
    """
    Действие обновление конфигурационных файлов
    """
    # ошибки, которые отображаются без подробностей
    native_error = (DistributiveError, FilesError, UpdateError,
                    TemplatesError,
                    BuilderError, GitError)

    successMessage = __("The profile was successfully updated")
    failedMessage = None
    interruptMessage = __("Profile update manually interrupted")

    # список задач для действия
    tasks = [
        {'name': 'check_build_run',
         'method': 'Builder.check_build_run()'},
        {'name': 'check_chroot_run',
         'method': 'Builder.check_chroot_run()'},
        {'name': 'allow_scan_binhost',
         'method': 'Builder.setVariable("cl_builder_binhost_scan_set",'
                   '"on",True)'
         },
        {'name': 'migrate_repository',
         'method': 'Builder.migrateCacheRepository('
                   'cl_builder_profile_url,cl_builder_profile_branch,'
                   'cl_builder_profile_storage)',
         'message': __("Repository transfer"),
         'condition': lambda Get: (Get('cl_builder_profile_url')
                and not (
                Get('cl_builder_profile_storage').is_local(
                 Get('cl_builder_profile_url'),
                 Get('cl_builder_profile_branch'))))

         },
        {'name': 'reconfigure_vars1',
         'method': 'Builder.invalidateVariables("cl_builder_profile_storage")',
         'depend': Tasks.has('migrate_repository')
         },
        {'name': 'check_datavars',
         'error': _("Profile not found in master"),
         'condition': lambda Get: not Get('cl_builder_profile_datavars')
         },
        {'name': 'drop_binhosts',
         'method': 'Builder.drop_binhosts(cl_builder_profile_datavars)'
         },
        {'name': 'reconfigure_vars',
         'method': 'Builder.reconfigureProfileVars(cl_builder_profile_datavars,'
                   'cl_builder_path)'
         },
        {'name': 'remove_old_reps',
         'foreach': 'cl_builder_remove_rep',
         'message': __("Remove the {eachvar:capitalize} repository"),
         'method': 'Builder.remove_repositories(eachvar)'
         },
        # {'name': 'reps_synchronization',
        #  'group': __("Repositories synchronization"),
        #  'tasks': [
        #      {'name': 'sync_reps',
        #       'foreach': 'cl_builder_profile_sync_rep',
        #       'message': __("Checking the {eachvar:capitalize} repository"),
        #       'method': 'Builder.syncRepositories(eachvar)',
        #       },
        #      {'name': 'regen_cache',
        #       'foreach': 'cl_builder_sync_overlay_rep',
        #       'essential': False,
        #       'method': 'Builder.regenCache(eachvar)',
        #       },
        #      {'name': 'eix_update',
        #       'message': __("Updating the eix cache for "
        #                     "{cl_builder_eix_repositories}"),
        #       'method': 'Builder.eixUpdate(cl_builder_repository_name)',
        #       },
        #      # save
        #      {'name': 'save',
        #       'method': 'Builder.save_build(cl_builder_build,'
        #                 'cl_builder_profile_datavars)',
        #       },
        #      # сообщение удачного завершения при обновлении репозиториев
        #      {'name': 'success_syncrep',
        #       'message': __("Synchronization finished"),
        #       'depend': (Tasks.success() & Tasks.has_any("sync_reps",
        #                                                  "sync_other_reps",
        #                                                  "emerge_metadata",
        #                                                  "eix_update")),
        #       }
        #  ]
        #  },
        {'name': 'reps_synchronization',
         'group': __("Setting up the profile"),
         'tasks': [
             {'name': 'set_profile',
              'message': __("Switching to profile "
                            "{cl_builder_profile_system_shortname}"),
              'method': 'Builder.set_profile('
                        'cl_builder_profile_system_shortname,cl_builder_path)'
              },
             # {'name': 'merge_utils',
             # 'message': __("Calculating dependencies"),
             # 'method': 'Builder.emerge("-console -pxe","-1",'
             #           '"sys-apps/calculate-utils")',
             # # TODO: возможно добавить параметр необходимости установки
             # 'condition': lambda Get: not isPkgInstalled(
             #     'sys-apps/calculate-utils', Get('cl_builder_path'))
             # },
             {'name': 'reconfigure',
              'message': __("The build is being configured"),
              'method': 'Builder.apply_templates(cl_builder_path,'
                        'cl_template_clt_set,True,None,False,"merge",'
                        'cl_builder_profile_datavars)',
              'condition': lambda Get: (
                  Get('update.cl_update_skip_setup_set') == 'off')
              },
             {'name': 'fix_settings',
              'message': __("Fixing the settings"),
              'method': 'Builder.apply_templates(cl_builder_path,'
                        'cl_template_clt_set,True,None,False,"sync",'
                        'cl_builder_profile_datavars)',
              'condition': lambda Get: Get('cl_templates_locate')
              },
             {'name': 'dispatch_conf',
              'message': __("Updating configuration files"),
              'method': 'Builder.dispatchConf(None,cl_builder_path)',
              'condition': lambda Get: Get('cl_dispatch_conf') != 'skip'
              },
         ]
         },
        {'name': 'failed',
         'error': __("Failed to update the profile"),
         'depend': (Tasks.failed() & Tasks.hasnot("interrupt") &
                    Tasks.success_all("check_build_run"))
         },
    ]
