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

# Copyright 2010-2013 Calculate Ltd. 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.utils.files import FilesError
from calculate.lib.utils.portage import isPkgInstalled
from calculate.install.install import (MigrationError, TemplatesError,
                                  InstallError,
                                  AutopartitionError, DistributiveError)

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':'reboot',
         'warning':__("To apply the changes, reboot the system"),
         'condition': lambda dv:(dv.Get('os_x11_video_drv') != \
                dv.Get('os_install_x11_video_drv') and \
                (dv.Get('os_x11_video_drv') in dv.Get('os_x11_kms_video_drv') \
                or dv.Get('os_install_x11_video_drv') \
                    in dv.Get('os_x11_kms_video_drv')))
        },
        {'name':'restart',
         'warning':__("To apply the changes, restart the X server"),
         'condition': lambda dv:(dv.Get('os_x11_video_drv') !=
                dv.Get('os_install_x11_video_drv') and
                (not dv.Get('os_x11_video_drv') in
                     dv.Get('os_x11_kms_video_drv') and
                 not dv.Get('os_install_x11_video_drv')
                    in dv.Get('os_x11_kms_video_drv')))
        }
        ]

    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 ClSetupUsersAction(ClSetupSystemAction):
    """
    Действие для настройки пользовательских параметров
    """
    addon_tasks = []
    templateTaskMessage = __("The user settings are being configured")
    successMessage = __("User settings configured!")
    failedMessage = __("Failed to configure the user 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))
        },
        ]
