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

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

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

from calculate.lib.cl_lang import setLocalTranslate
from calculate.core.server.decorators import Dec
from calculate.core.server.func import uniq
#from calculate.api.cert_cmd import find_id_cert
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 not 'all' in result:
            result.append('all')
        return result

    #def get(self):
        #req_id = self.Get('cl_req_id')
        #data_path = self.Get('cl_core_data')
        
        #cert_file =  data_path + '/client_certs/%s.crt' %req_id
        #if os.path.exists(cert_file):
            #fp = open(cert_file, 'r')
            #cert = fp.read()
            #fp.close()
            #certobj = OpenSSL.crypto.load_certificate \
                      #(OpenSSL.SSL.FILETYPE_PEM, cert)
            #com = certobj.get_extension(certobj.get_extension_count()-1)\
#                                                            .get_data()
            #return com.split(':')[1]
        #return ''

    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 Dec.rightsMethods.keys():
            right_list += Dec.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 Dec.rightsMethods.keys():
                right_list += Dec.rightsMethods[key]

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

        return results
