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

# Copyright 2017 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.configparser import ConfigParser
from calculate.lib.utils.files import pathJoin, readFile, writeFile
from calculate.lib.utils.text import _u8
import re
from os import path
from calculate.lib.cl_lang import getLazyLocalTranslate, setLocalTranslate
from collections import MutableMapping

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


class Admins(MutableMapping):
    """
    Объект работы с информацией о локальных администраторах
    """
    section = "admin"

    def __init__(self, dv, chroot=False):
        self.dv = dv
        self.cp = ConfigParser(strict=False)
        if chroot:
            self.ini_path = pathJoin(
                dv.Get('cl_chroot_path'),
                dv.Get('core.cl_core_admin_path'))
        else:
            self.ini_path = dv.Get('core.cl_core_admin_path')
        self.cert_database = dv.Get('core.cl_core_database')

        if path.exists(self.ini_path):
            self.cp.read(self.ini_path, encoding="utf-8")

    def __getitem__(self, item):
        return _u8(self.cp.get(self.section, item, fallback=""))

    def __contains__(self, item):
        return self.cp.has_option(self.section, item)

    def __len__(self):
        return len(list(iter(self)))

    def __iter__(self):
        if not self.cp.has_section(self.section):
            return iter(())
        else:
            return iter(_u8(x) for x in self.cp[self.section])

    def has_certificate(self, user):
        """
        Проверить: выдавался ли сертификат указанному пользователю
        """
        certdata = readFile(self.cert_database, grab=True)
        return bool(re.search("^\S+\s+(?:\S+\s+){6}%s\s*$" % user,
                              certdata, flags=re.M))

    def __setitem__(self, item, value):
        if not self.cp.has_section(self.section):
            self.cp.add_section(self.section)
        self.cp[self.section][item] = value

    def __delitem__(self, item):
        if self.cp.has_section(self.section):
            self.cp.remove_option(self.section, item)

    def save(self):
        with writeFile(self.ini_path) as f:
            self.cp.write(f)

    def clear(self):
        self.cp.remove_section(self.section)
