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

# Copyright 2010-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
from calculate.install.distr import DistributiveError
from calculate.install.migrate_users import MigrationError
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.utils.portage import isPkgInstalled
from calculate.install.install import InstallError
from calculate.install.variables.autopartition import AutopartitionError

setLocalTranslate('cl_install3', sys.modules[__name__])
__ = getLazyLocalTranslate(_)


class ClSetupVideoAction(Action):
    """
    Действие для настройки параметров видео
    """
    # ошибки, которые отображаются без подробностей
    native_error = (FilesError, MigrationError, TemplatesError,
                    InstallError, AutopartitionError, DistributiveError)

    templateTaskMessage = __("Video settings are being configured")
    successMessage = __("Video settings configured!")
    failedMessage = __("Failed to configure the video settings!")
    interruptMessage = __("Configuration manually interrupted")

    prev_tasks = [
        # проверить и настроить параметры для nvidia драйвера
        {'name': 'drop_xorg_log',
         'method': 'Install.drop_xorg_logs()',
         'condition': lambda Get: (
            Get('os_install_x11_video_drv_prev')
            != Get('os_install_x11_video_drv'))
        },
    ]

    addon_tasks = [
        {'name': 'check_video',
         'message': __("Checking the video driver"),
         'method': 'Install.checkVideoDriver()',
         'condition': lambda: isPkgInstalled('xorg-server')
         },
        {'name': 'setupvideo',
         'condition': lambda Get: Get('cl_setup') == 'video'
         },
        {'name': 'setupvideo:reboot',
         'warning': __("To apply the changes, reboot the system"),
         'condition': lambda Get: ((Get('os_x11_video_drv') !=
                                    Get('os_install_x11_video_drv') and
                                    (Get('os_x11_video_drv') in Get(
                                        'os_x11_kms_video_drv')
                                     or Get('os_install_x11_video_drv')
                                     in Get('os_x11_kms_video_drv')))
                                   and Get('os_install_root_type') != 'livecd')
         },
        {'name': 'setupvideo:restart',
         'warning': __("To apply the changes, restart the X server"),
         'condition': lambda Get: ((Get('os_x11_video_drv') !=
                                    Get('os_install_x11_video_drv') and
                                    (not Get('os_x11_video_drv') in
                                         Get('os_x11_kms_video_drv') and
                                     not Get('os_install_x11_video_drv')
                                         in Get('os_x11_kms_video_drv')))
                                   and Get('os_install_root_type') != 'livecd')
         }
    ]

    def __init__(self):
        # список задач для действия
        self.tasks = self.prev_tasks + [
            {'name': 'apply_templates',
             'message': self.templateTaskMessage,
             # наложить шаблоны на текущий дистрибутив, включая clt шаблоны
             # без использования фильтров по clt шаблонам
             'method': 'Install.applyTemplates(cl_source,cl_template_clt_set,'
                       'cl_merge_set,None)',
             }]
        # выполнить дополнительные задачи
        self.tasks.extend(self.addon_tasks)
        Action.__init__(self)


class ClSetupSystemAction(ClSetupVideoAction):
    """
    Объект настройки всех параметров системы
    """
    prev_tasks = []
    templateTaskMessage = __("The system is being configured")
    successMessage = __("System configured!")
    failedMessage = __("Failed to configure the system!")


class ClSetupAudioAction(ClSetupSystemAction):
    """
    Действие для настройки аудио параметров
    """
    addon_tasks = []
    prev_tasks = []
    templateTaskMessage = __("The audio settings are being configured")
    successMessage = __("Audio settings configured!")
    failedMessage = __("Failed to configure the audio parameters!")


class ClSetupThemesAction(ClSetupSystemAction):
    """
    Действие для настройки тем
    """
    addon_tasks = []
    prev_tasks = [
        {'name': 'init_themes',
         'method': 'Install.init_themes()'
         },
    ]
    templateTaskMessage = __("The themes are being configured")
    successMessage = __("Themes configured!")
    failedMessage = __("Theme configuration failed!")


class ClSetupLocaleAction(ClSetupSystemAction):
    """
    Действие для настройки языковых параметров
    """
    addon_tasks = []
    prev_tasks = []
    templateTaskMessage = \
        __("The localization and time options are being configured")
    successMessage = __("System configured!")
    failedMessage = __("Failed to configure the system!")


class ClSetupNetworkAction(ClSetupSystemAction):
    """
    Действие для настройки аудио параметров
    """
    addon_tasks = []
    templateTaskMessage = __("The network settings are being configured")
    successMessage = __("Network settings configured!")
    failedMessage = __("Failed to configure the network settings!")


class ClSetupSessionAction(ClSetupSystemAction):
    """
    Действие для настройки пользовательских параметров
    """
    addon_tasks = []
    templateTaskMessage = __("The session settings are being configured")
    successMessage = __("Session settings configured!")
    failedMessage = __("Failed to configure the session settings!")


class ClSetupBootAction(ClSetupSystemAction):
    """
    Действие для настройки параметров загрузки
    """
    templateTaskMessage = __("The boot parameters are being configured")
    successMessage = __("Boot parameters configured!")
    failedMessage = __("Failed to configure the boot parameters!")

    prev_tasks = []
    addon_tasks = [
        # установить загрузчик
        {'name': 'prepare_bootloader',
         'message': _("Installing the bootloader"),
         'method': 'Install.prepareBoot(cl_image)',
         'condition': (lambda Get: (Get('os_install_mbr') or
                                    Get('os_install_uefi_set') == 'on') and
                                   Get('os_root_type') != 'livecd' and
                                   Get('os_install_scratch') == 'off')
         },
        {'name': 'no_scratch',
         'warning': _("The builder mode is no longer supported"),
         'condition': lambda Get: Get('os_install_scratch') == 'on'
         },
    ]
