# -*- 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.lib.variables.system import RootType
from calculate.update.emerge_parser import EmergeError
from calculate.update.update import UpdateError
from ..datavars import BuilderError
from calculate.lib.utils.git import GitError
from calculate.install.distr import DistributiveError, IsoDistributive
from calculate.builder.variables.action import Actions

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


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

    successMessage = __("Image created successfully")
    failedMessage = None
    interruptMessage = __("Image creating manually interrupted")

    # список задач для действия
    tasks = [
        {'name': 'check_build_run',
         'method': 'Builder.check_build_run()'},
        {'name': 'check_chroot_run',
         'method': 'Builder.check_chroot_run()'},
        {'name': 'clear_log',
         'method': 'Builder.clear_log(cl_builder_id_path)',
         },
        {'name': 'remount_flash',
         'method': 'Builder.remount_rw(cl_builder_flash_path)',
         'condition': lambda Get: Get('cl_builder_rescratch_set') == 'on'
         },
        {'name': 'iso_linux_migrate',
         'method': 'Builder.iso_migrate(cl_builder_flash_path)',
         'condition': lambda Get: Get('cl_builder_rescratch_set') == 'on'
         },
        {'name': 'remount_data',
         'method': 'Builder.remount_rw(cl_isoscan_base_path)',
         'condition': lambda Get: (
             Get('os_root_type_ext') in RootType.IsoScanGrub)
         },
        {'name': 'prepare_action',
         'method': 'Builder.set_builder_action("prepare")',
         },
        {'name': 'apply_template',
         'message': __("Configuring build"),
         'method': 'Builder.applyTemplates(cl_builder_target,False,False,None)',
         },
        # обновить темы
        {'name': 'update_themes',
         'message': __("Updating themes"),
         'method': 'Builder.apply_templates(cl_builder_path,'
                   'cl_template_clt_set,True,None,False,"merge",'
                   'cl_builder_linux_datavars,True)',
         'condition': lambda Get: Get("cl_builder_update_themes_set") == 'on'
         },
        {'name': 'prelink',
         'message': __("Executing prelink"),
         'method': 'Builder.chroot_command(cl_builder_path,"prelink",'
                   '"-afmR")',
         'condition': lambda Get: Get('cl_builder_prelink_set') == 'on'
         },
        {'name': 'reconfigure_vars1',
         'method': 'Builder.invalidateVariables("cl_builder_linux_datavars")',
         },
        # обновить темы
        {'name': 'update_dracut',
         'message': __("Updating initramfs"),
         'method': 'Builder.update_dracut(cl_builder_path)',
         'condition': lambda Get: Get("cl_builder_update_themes_set") == 'on'
         },
        # получить видеодрайверы
        {'name': 'fetch_video_drivers',
         'group': __("Fetching video drivers"),
         'tasks': [
             {'name': 'fetch_drivers',
              'method': 'Builder.fetch_drivers(cl_builder_path,'
                        'cl_builder_linux_distdir,cl_builder_linux_pkgdir)',
              'condition': lambda Get: Get('cl_builder_videodrv_set') == 'on'
              },
             {'name': 'create_video_data',
              'message': __("Creating install video driver data"),
              'method': 'Builder.create_video_data(cl_builder_path,'
                        'cl_builder_repository_data)',
              'condition': lambda Get: Get('cl_builder_videodrv_set') == 'on'
              },
         ]
         },
        {'name': 'remove_video_drivers',
         'method': 'Builder.remove_video_drivers(cl_builder_path)',
         'condition': lambda Get: Get('cl_builder_videodrv_set') == 'off'
         },
        {'name': 'trim_reps',
         'foreach': 'cl_builder_sync_rep',
         'message': __("Cleaning the history of the {eachvar:capitalize} "
                       "repository"),
         'method': 'Builder.trimRepositories(eachvar)',
         'condition': lambda Get: (
             Get('cl_builder_sync_rep') and
             Get('cl_builder_keep_tree_set') == 'on')
         },
        {'name': 'creating_live_image',
         'group': __("Creating live image"),
         'tasks': [
             # закрепить подключенные данные
             {'name': 'detach',
              'method': 'Builder.detach_target(cl_builder_target)',
              },
             {'name': 'umount_system',
              'message': __("Umount build system resources"),
              'method': 'Builder.umount_system(cl_builder_target)',
              'condition': lambda Get: Get('cl_builder_build')
              },
             {'name': 'prepare_image',
              'method': 'Builder.prepare_image(cl_builder_image)',
              'condition': lambda Get: isinstance(Get('cl_builder_image'),
                                                  IsoDistributive)
              },
             {'name': 'squash_action',
              'method': ('Builder.set_builder_action("%s")'
                         % Actions.ImageSquash),
              },
             {'name': 'count_files',
              'method': 'Builder.recount_files(cl_builder_path,'
                        'cl_builder_squash_exclude)'
              },
             {'name': 'create_dev_nodes',
              'method': 'Builder.create_dev_nodes(cl_builder_path)'
              },
             {'name': 'apply_template',
              'message': __("Configuring squash filesystem image"),
              'method': 'Builder.applyTemplates(cl_builder_target,'
                        'False,False,None)',
              },
             {'name': 'squash_action',
              'method': 'Builder.set_builder_action("%s")' % Actions.ImageIso,
              },
             {'name': 'protect_off',
              'method': 'Builder.setVariable("cl_protect_use_set","off",True)'
              },
             # сборка iso
             {'name': 'remove_list_digest',
              'method': "Builder.remove_list_digest(cl_builder_image_filename)"
              },
             {'name': 'unpack',
              'message': __("Pack squash filesystem image"),
              'method': 'Install.unpack(cl_builder_target, cl_builder_image,'
                        '"0")',
              },
             {'name': 'isohybrid',
              'message': __("Appling isohybrid feature for image"),
              'method': 'Builder.isohybrid(cl_builder_image_filename)',
              'condition': lambda Get: Get('cl_builder_isohybrid_set') == 'on'
              },
             {'name': 'create_package_list',
              'message': __("Creating package list"),
              'method': 'Builder.create_package_list(cl_builder_path,'
                        'cl_builder_image_filename)',
              },
             {'name': 'umount_system!:mount_system',
              'warning': _("Restore build system resources"),
              'method': 'Builder.mount_target(cl_builder_target)',
              'condition': lambda Get: Get('cl_builder_build')
              },
             {'name': 'flash_menu',
              'method': 'Builder.set_builder_action("%s")' % Actions.ImageMenu,
              'condition': lambda Get: Get('cl_builder_rescratch_set') == 'on'
              },
             {'name': 'flash_menu:remove_flash_tmp',
              'method': 'Builder.remove_flash_tmp()'
              },
             {'name': 'flash_menu:sync_vmlinuz',
              'message': __("Extracting kernels from ISO images"),
              'method': 'Builder.sync_vmlinuz(cl_builder_flash_path)'
              },
             {'name': 'flash_menu:update_menu',
              'message': __("Recreating ISO image menu"),
              'method': 'Builder.update_menu(cl_builder_flash_path)',
              },
             {'name': 'grub_menu',
              'method': 'Builder.set_builder_action("%s")' % Actions.ImageMenu,
              'condition': lambda Get: (
                  Get('cl_builder_grub_refresh_set') == 'on')
              },
             {'name': 'grub_menu:update_grub_menu',
              'message': __("Creating the ISO images menu"),
              'method': 'Builder.create_iso_grub_cfg(cl_builder_livemenu_path)',
              'condition': lambda Get: (
                  Get('builder.cl_builder_livemenu_path') != "")
              },
         ]
         },
        {'name': 'failed',
         'error': __("Creating the image is failed"),
         'depend': (Tasks.failed() & Tasks.hasnot("interrupt") &
                    Tasks.success_all("check_build_run"))
         },
    ]
