# -*- 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 os import path
from calculate.core.server.func import Action, Tasks
from calculate.lib.cl_lang import setLocalTranslate, getLazyLocalTranslate
from calculate.lib.utils.files import FilesError, listDirectory
from calculate.lib.utils.mount import isMount
from calculate.desktop.desktop import DesktopError
from calculate.lib.cl_template import TemplatesError

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


class ClDesktopLogoutAction(Action):
    """
    Вывести пользователя из X сессии
    """
    # ошибки, которые отображаются без подробностей
    native_error = (FilesError, DesktopError, TemplatesError)

    successMessage = __("User logged out!")
    failedMessage = __("Unable to log out")
    interruptMessage = __("Logout manually interrupted")

    # список задач для действия
    tasks = [
        {'name': 'user_logout',
         'method': 'Desktop.userLogout(cl_desktop_login)',
         },
        {'name': 'wait_logout',
         'message': __("Waiting for the logout"),
         'method': 'Desktop.waitLogout(cl_desktop_login,300)'}
    ]

def need_skel(Get):
    home_path = Get('ur_home_path')
    if path.exists(home_path):
        files = listDirectory(home_path, onlyDir=True)
        if len(files) == 1 and ".calculate" in files:
            return True
        return False
    return True


class ClDesktopAction(Action):
    """
    Настроить пользовательский профиль
    """
    # ошибки, которые отображаются без подробностей
    native_error = (FilesError, DesktopError, TemplatesError)

    successMessage = __("User account {ur_login} has been "
                        "successfully configured")
    failedMessage = __("Failed to configure the user account")
    interruptMessage = __("Configuration manually interrupted")

    # список задач для действия
    tasks = [
        {'name': 'need_skel',
         'condition': need_skel
        },
        # создать домашниюю директорию
        {'name': 'create_home',
         'message': __("Creating the home directory for {ur_login}"),
         'method': 'Desktop.createUserDir(ur_login,ur_uid,ur_gid,ur_home_path)',
         'condition': lambda dv: not path.exists(dv.Get('ur_home_path'))
         },
        # используется ли шифрование
        {'name': 'crypt',
         'condition': lambda dv: (not isMount(dv.Get('ur_home_path')) and
                                  dv.Get('ur_home_crypt_set') == 'on' and
                                  (not dv.isModuleInstalled("install") or
                                   dv.Get('install.cl_autologin') != dv.Get(
                                       'ur_login')))
         },
        # подготовить шифрованный профиль пользователя для работы с .icon
        {'name': 'crypt:prepare_icon',
         'method': 'Desktop.prepareFace(ur_home_path)',
         'condition': lambda Get: Get('ur_domain_set') == 'off'
         },
        # подключить шифрованные данные
        {'name': 'crypt:ecryptfs',
         'message': __("Mounting encrypted data"),
         'method': 'Desktop.createCryptDir(ur_login,ur_uid,ur_gid,'
                   'ur_home_path,False)'
         },
        {'name': 'need_skel:sync_skel',
         'message': _("Copying skel data"),
         'method': 'Desktop.syncSkel(ur_home_path,ur_uid,ur_gid)'
         },
        # настроить пользовательских профиль шаблонами
        {'name': 'user_profile',
         'message': __("Setting up the user profile"),
         'method': 'Desktop.applyTemplates(None,False,'
                   'False,None)',
         'condition': lambda Get: (Get('cl_desktop_force_setup_set') == 'on' or
                                   Get('cl_desktop_update_profile_set') == 'on')
         },
        {'name': 'fast_login',
         'method': 'Desktop.setFastlogin(ur_login)',
         'essential': False,
         'condition': lambda Get: Get('ur_domain_set') == 'off'
         },
        # отключить ресурсы подключенные в каталоге пользователя
        {'name': 'umount_userres',
         'message': _("Unmouning user resources"),
         'method': 'Desktop.umountUserRes(ur_mount_dirs)',
         'condition': lambda dv: dv.Get('ur_mount_dirs'),
         'depend': Tasks.failed()},
        {'name': 'ecryptfs:umount_homedir',
         'method': 'Desktop.umountUserRes(ur_home_path)',
         'depend': Tasks.failed()}
    ]
