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

# Copyright 2011-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.

from calculate.lib.datavars import Variable, VariableError
import sys
import re

from calculate.lib.cl_lang import setLocalTranslate
from calculate.core.server.loaded_methods import LoadedMethods
from calculate.core.server.func import uniq

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


class VariableClCoreGroup(Variable):
    """
    Certificate Group
    """
    type = "choiceedit"
    opt = ["cl_core_group"]
    metavalue = "GROUP_NAME"
    untrusted = True

    def init(self):
        self.help = _("Set the certificate group")
        self.label = _("Group name")

    def choice(self):
        group_rights = self.Get('cl_core_group_rights_path')

        t = open(group_rights, 'r').read()
        result = []
        for line in t.splitlines():
            words = line.split()
            if words and len(words):
                if not words[0].startswith('#'):
                    result.append(words[0])
        if 'all' not in result:
            result.append('all')
        return result

    def check(self, group):
        if not group:
            raise VariableError(_("Group name is a required parameter"))
        name_re = re.compile("^[a-zA-Z_0-9]{2,20}$")
        if not name_re.findall(group):
            raise VariableError(
                _('The group name may only contain words, '
                  'digits and underline symbols') + '\n' +
                _('The group name must consist of 2 to 20 symbols'))
        group_rights = self.Get('cl_core_group_rights_path')

        if group == 'all':
            return
        t = open(group_rights, 'r').read()
        find = False
        for line in t.splitlines():
            words = line.split()
            if words[0].startswith('#'):
                continue
            if group == words[0]:
                find = True
        if self.Get('cl_action') == "add" and find:
            raise VariableError(_('Group %s already exists!') % group)
        elif self.Get('cl_action') != "add" and not find:
            raise VariableError(_("Group %s does not exist") % group)


class VariableClCoreGroupRights(Variable):
    """
    Certificate Group
    """
    type = "choice-list"
    opt = ["--group-rights"]
    metavalue = "right[,right2[..]]"

    def init(self):
        self.help = _("Group permissions")
        self.label = _("Group permissions")

    def choice(self):
        right_list = []
        for key in LoadedMethods.rightsMethods.keys():
            right_list += LoadedMethods.rightsMethods[key]

        uniq_right_list = uniq(right_list)
        uniq_right_list.sort()
        return uniq_right_list

    def get(self):
        group_name = self.Get('cl_core_group')
        group_rights = self.Get('cl_core_group_rights_path')

        t = open(group_rights, 'r').read()
        results = []
        for line in t.splitlines():
            words = line.split(' ', 1)
            if words[0] == group_name:
                methods = words[1].split(',')
                for i in methods:
                    results.append(i.strip())

        if group_name == 'all' and results == []:
            right_list = []
            for key in LoadedMethods.rightsMethods.keys():
                right_list += LoadedMethods.rightsMethods[key]

            uniq_right_list = uniq(right_list)
            uniq_right_list.sort()
            return uniq_right_list

        return results
