# -*- 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")

    addon_tasks = [
        # проверить и настроить параметры для nvidia драйвера
        {'name': 'check_video',
         'message': __("Checking the video driver"),
         'method': 'Install.checkVideoDriver()',
         'condition': lambda: isPkgInstalled('xorg-server')
         },
        {'name': 'setup_opengl',
         'message': __("Configuring OpenGL"),
         'method': 'Install.setupOpenGL()',
         '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 = [
            {'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):
    """
    Объект настройки всех параметров системы
    """
    templateTaskMessage = __("The system is being configured")
    successMessage = __("System configured!")
    failedMessage = __("Failed to configure the system!")


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


class ClSetupLocaleAction(ClSetupSystemAction):
    """
    Действие для настройки языковых параметров
    """
    addon_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!")

    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'
         },
        # изменить IO планировщик
        {'name': 'change_ioscheduler',
         'message': _("Changing the I/O scheduler"),
         'method': 'Install.changeScheduler(os_install_kernel_scheduler)',
         'condition': (lambda dv: dv.Get('os_root_type') != 'livecd' and
                                  dv.Select('os_disk_parent',
                                            where='os_disk_mount',
                                            eq='/', limit=1))
         },
    ]
