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

# Copyright 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.lib.datavars import (VariableInterface, VariableError)
from calculate.unix.unix import UnixGroups, UnixUsers

_ = lambda x: x
from calculate.lib.cl_lang import (setLocalTranslate, getLazyLocalTranslate)

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


class Actions(object):
    UserAdd = "useradd"
    UserMod = "usermod"
    UserDel = "userdel"
    GroupAdd = "groupadd"
    GroupMod = "groupmod"
    GroupDel = "groupdel"
    Passwd = "passwd"
    Setup = "setup"
    GroupShow = "groupshow"
    UserShow = "usershow"

    UserExists = (UserMod, UserDel, Passwd)
    GroupExists = (GroupMod, GroupDel)
    All = (
        UserAdd, UserMod, UserDel, GroupAdd, GroupMod, GroupDel, Setup, Passwd)
    New = (UserAdd, GroupAdd)
    Exists = (Passwd, UserMod, UserDel, GroupMod, GroupDel, UserShow, GroupShow)


class ExistsUserHelper(VariableInterface):
    attribute = ""

    def get_exists(self):
        user = self.Get('ur_unix_user_object')
        if user:
            val = getattr(user, self.attribute)
            if type(val) == bool:
                return "on" if val else "off"
            else:
                return val
        return ""


class UnixGroupHelper(VariableInterface, UnixGroups):
    exception = VariableError

    @property
    def ldap_connect(self):
        return self.Get('ldap.cl_ldap_connect')

    @property
    def groups_dn(self):
        return self.Get('ld_unix_groups_dn')


class UnixUserHelper(VariableInterface, UnixUsers):
    exception = VariableError

    @property
    def ldap_connect(self):
        return self.Get('ldap.cl_ldap_connect')

    @property
    def users_dn(self):
        return self.Get('ld_unix_users_dn')


class UnixUserPropertyHelper(VariableInterface):
    """
    Получение атрибутов текущего пользователя
    """


class UnixActionHelper(VariableInterface):
    """
    Разделение на методы в зависимости от действия
    """
    fallback = ""

    def get_new(self):
        if "list" in self.type:
            return []
        return ""

    def get_exists(self):
        if "list" in self.type:
            return []
        return ""

    def check_new(self, value):
        pass

    def check_exists(self, value):
        pass

    def choice_new(self):
        return []

    def choice_exists(self):
        return []

    def _new(self, value):
        return value in Actions.New

    def _exists(self, value):
        return value in Actions.Exists

    def get(self):
        unix_action = self.Get('unix.cl_unix_action')
        if self._new(unix_action):
            return self.get_new()
        elif self._exists(unix_action):
            return self.get_exists()
        return self.fallback

    def check(self, value):
        unix_action = self.Get('unix.cl_unix_action')
        if self._new(unix_action):
            return self.check_new(value)
        elif self._exists(unix_action):
            return self.check_exists(value)

    def choice(self):
        unix_action = self.Get('unix.cl_unix_action')
        if self._new(unix_action):
            return self.choice_new()
        elif self._exists(unix_action):
            return self.choice_exists()

class FieldsHelper(VariableInterface):
    type = "choice-list"
    element = "selecttable"
    opt = ["--fields"]
    metavalue = "FIELDS"
    alias_variable = ""

    def init(self):
        self.label = _("Fields")
        self.help = _("fields for display")

    def choice(self):
        data = self.Get(self.alias_variable)
        return [(x, self.parent.getInfo(y).label) for x, y in data]

    def get(self):
        return [x for x, y in self.Get(self.alias_variable)]


class ShowFieldsHelper(VariableInterface):
    type = "list"
    alias_variable = ""
    source_variable = ""

    def get(self):
        mapping = dict(self.Get(self.alias_variable))
        return [mapping[x] for x in self.Get(self.source_variable)]
