# -*- 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 calculate.core.server.core_interfaces import MethodsInterface

from calculate.lib.utils.files import readLinesFile
from calculate.lib.utils.common import getPagesInterval
from calculate.lib.cl_lang import getLazyLocalTranslate, setLocalTranslate

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


class Groups(MethodsInterface):
    """
    Объект работы с группами прав
    """

    def show_groups_meth(self, page_count, page_offset):
        """
        Отобразить таблицу с группами
        """
        dv = self.clVars
        list_group_name = sorted(dv.Choice('cl_core_group'))

        if not list_group_name:
            self.printSUCCESS(_("No groups"))

        head = [_('Groups'), _('Permissions')]
        body = []
        fields = ['cl_core_group', '']

        for group in list_group_name[page_offset:page_offset + page_count]:
            dv.Set('cl_core_group', group)
            group_rights = ', '.join(dv.Get('cl_core_group_rights'))
            body.append([group, group_rights])

        if body:
            self.printTable(_("List of available groups"), head, body,
                            fields=fields, onClick='core_detail_group',
                            addAction='core_group_add')
            num_page, count_page = getPagesInterval(page_count, page_offset,
                                                    len(list_group_name))
            self.printSUCCESS(_('page %d from ') % num_page + str(count_page))
        return True

    def change_group_meth(self, cl_group_name, cl_group_rights,
                          group_rights_file):
        """
        Изменить группу
        """
        changed_flag = False
        result = []

        for line in readLinesFile(group_rights_file):
            if line.startswith('#') or not line:
                result.append(line)
                continue
            words = line.split(' ', 1)
            # first word in line equal name input method
            if words[0] == cl_group_name:
                line = cl_group_name + ' ' + ','.join(cl_group_rights)
                changed_flag = True
            result.append(line)

        if cl_group_name == 'all' and not changed_flag:
            result.append(cl_group_name + ' ' + ','.join(cl_group_rights))

        fd = open(group_rights_file, 'w')
        for lines in result:
            fd.write(lines + '\n')
        fd.close()
        return True

    def add_group_meth(self, cl_group_name, cl_group_rights, group_rights_file):
        """
        Добавить группу
        """
        result = []
        for line in readLinesFile(group_rights_file):
            if line.startswith('#') or not line:
                result.append(line)
                continue
            words = line.split(' ', 1)
            # first word in line equal name input method
            if words[0] == cl_group_name:
                self.printERROR(_('Group %s already exists!')
                                % cl_group_name)
                return False
            result.append(line)

        result.append(cl_group_name + ' ' + ",".join(cl_group_rights))

        fd = open(group_rights_file, 'w')
        for lines in result:
            fd.write(lines + '\n')
        fd.close()
        return True

    def del_group_meth(self, cl_group_name, group_rights_file):
        """
        Удалить группу
        """
        result = []
        for line in readLinesFile(group_rights_file):
            if line.startswith('#') or not line:
                result.append(line)
                continue
            words = line.split(' ', 1)
            # first word in line equal name input method
            if words[0] != cl_group_name:
                result.append(line)

        fd = open(group_rights_file, 'w')
        for lines in result:
            fd.write(lines + '\n')
        fd.close()
        return True
