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

# Copyright 2010 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.
from cl_client import client, __app__, __version__
from cl_opt import opt
import sys
from cl_share_cmd import share_cmd

# Перевод сообщений для программы
from cl_lang import lang
lang().setLanguage(sys.modules[__name__])

# Использование программы
USAGE = _("%prog [options] user")

# Коментарии к использованию программы
COMMENT_EXAMPLES = _("Mount resources and synchronize the user profile")

# Пример использования программы
EXAMPLES = _("%prog user_name")

# Описание программы (что делает программа)
DESCRIPTION = _("Mount resources and synchronize the user profile")

# Опции командной строки
CMD_OPTIONS = [{'longOption':"login",
                'help':_("mount all user resources and synchronize the "
                         "user profile")},
               {'longOption':"logout",
                 'help':_("synchronize the user profile and unmount "
                          "user resource")},
               {'longOption':"nosync",
                 'help':_("do not synchronize user preferences; used "
                          "in conjunction with 'login' or 'logout'")},
               {'longOption':"set"},
               {'longOption':"progress",
                'help':_("show the progress bar at xdm startup")}]

class sync_cmd(share_cmd):
    def __init__(self):
        setpos = \
            filter(lambda x:x[1].get('longOption')=="set",
            enumerate(CMD_OPTIONS))[0][0]
        CMD_OPTIONS[setpos] = opt.variable_set[0]
        # Объект опций командной строки
        self.optobj = opt(\
            package=__app__,
            version=__version__,
            usage=USAGE,
            examples=EXAMPLES,
            comment_examples=COMMENT_EXAMPLES,
            description=DESCRIPTION,
            option_list=CMD_OPTIONS + opt.variable_view+opt.color_control,
            check_values=self.checkOpts)
        # Создаем объект логики
        self.logicObj = client()
        # Создаем переменные
        self.logicObj.createClVars()
        # Названия несовместимых опций
        self.optionsNamesIncompatible = ["login", "logout"]
        # Названия обязательных опций
        self.optionsNamesRequired = self.optionsNamesIncompatible

    def getOptionsRequired(self, optObj):
        """Получаем обязательные опции"""
        retList = []
        for nameOpt in self.optionsNamesRequired:
            retList.append(getattr(optObj, nameOpt))
        return retList

    def _getNamesAllSetOptions(self):
        """Выдает словарь измененных опций"""
        setOptDict = self.optobj.values.__dict__.items()
        defaultOptDict = self.optobj.get_default_values().__dict__.items()
        return dict(set(setOptDict) - set(defaultOptDict)).keys()

    def getStringIncompatibleOptions(self):
        """Форматированная строка несовместимых опций разделенных ','"""
        listOpt = list(set(self.optionsNamesIncompatible) &\
                       set(self._getNamesAllSetOptions()))
        return ", ".join(map(lambda x: len(x) == 1 and "'-%s'"%x or "'--%s'"%x,\
                             listOpt))

    def checkOpts(self, optObj, args):
        """Проверка опций командной строки"""
        optionsRequired = self.getOptionsRequired(optObj)
        if not args:
            options = [optObj.color, optObj.v, optObj.filter, optObj.xml]
            if not filter(lambda x: x, options):
                errMsg = _("no such argument")+":"+" %s" %USAGE.split(" ")[-1]
                self.optobj.error(errMsg)
                return False
        elif len(filter(lambda x: x, optionsRequired))>1:
                errMsg = _("incompatible options")+":"+" %s"\
                            %self.getStringIncompatibleOptions()
                self.optobj.error(errMsg)
                return False
        elif not filter(lambda x: x, optionsRequired):
            errMsg = _("required option")+":"+" %s"\
                %" or ".join(map(lambda x:\
                    len(x) == 1 and "'-%s'"%x or "'--%s'"%x,\
                    self.optionsNamesRequired))
            self.optobj.error(errMsg)
            return False
        if len(args)>1:
            errMsg = _("incorrect argument") + ":" + " %s" %" ".join(args)
            self.optobj.error(errMsg)
            return False
        if not optObj.v:
            if optObj.filter:
                errMsg = _("incorrect option") + ":" + " %s" %"--filter" +\
                ": " + _("used with option '-v'")
                self.optobj.error(errMsg)
                return False
            if optObj.xml:
                errMsg = _("incorrect option") + ":" + " %s" %"--xml" +\
                ": " + _("used with option '-v'")
                self.optobj.error(errMsg)
                return False
        return optObj, args

    def setUserName(self, userName):
        """Установка имени пользователя"""
        self.logicObj.clVars.Set("ur_login", userName, True)

    def mountUserResAndSync(self, sync=True, progress=False):
        """Монтирование ресурсов и синхронизация при входе"""
        userName =  self.logicObj.clVars.Get("ur_login")
        return self.logicObj.mountUserResAndSync(userName, sync=sync,
                                                 progress=progress)

    def umountUserResAndSync(self, sync=True, progress=False):
        """Отмонтирование ресурсов и синхронизация при выходе"""
        userName =  self.logicObj.clVars.Get("ur_login")
        return self.logicObj.umountUserResAndSync(userName, sync=sync,
                                                  progress=progress)
