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

# Copyright 2008-2010 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.
import sys

from cl_print import color_print
from cl_datavars import DataVars

# translate language
import cl_lang
tr = cl_lang.lang()
tr.setLocalDomain('cl_lib')
tr.setLanguage(sys.modules[__name__])

class services(color_print):
    '''Общие методы для серверных программ,

    Методы для работы с сервисами'''
    clLibVars = False

    def createClLibVars(self, clLibVars=False):
        """Создает объект библиотечных переменных"""
        if not clLibVars:
            clLibVars = DataVars()
            # Заменяем значения переменных переменными из env файлов
            clLibVars.flIniFile()
            # Устанавливаем у объекта атрибут объект переменных
            self.clLibVars = clLibVars
        return True

    def allServicesApi(self):
        self.createClLibVars(clLibVars=self.clLibVars)
        apiDict = self.clLibVars.Get('cl_api')
        if not apiDict or not type(apiDict) in dict:
            return []
        apiFiles = apiDict.keys()
        apiObjects = []
        for apiFile  in apiFiles:
            importPath, moduleName = os.path.split(apiFile)
            if not importPath in sys.path:
                sys.path.insert(0, importPath)
            try:
                className = getattr(__import__(moduleName,
                                               globals(), locals(),
                                               ['serviceAPI']),
                                    'serviceAPI')
            except (ImportError, AttributeError):
                self.printERROR(_("Can not import module %s")% apiFile)
                return False
            try:
                apiObjects.append(className())
            except:
                self.printERROR(_("Can not create API object"))
                self.printERROR(_("Module %s")% apiFile)
                return False
        return apiObjects

    def stopSetupAllServices():
        """Stopped all setup services"""
        allServObjs = self.allServicesApi()
        allSetupServObjs = filter(lambda x: x.isSetup(), allServObjs)
        if allServObjs is False:
            return False
        def smpPrioritet(objectA, objectB):
            '''Comparison of the run priorities of objects

            to sort in descending order
            '''
            prioritetA = objectA.getRunPrioritet()
            prioritetB = objectB.getRunPrioritet()
            if prioritetA == prioritetB:
                return 0
            elif prioritetA < prioritetB:
                return 1
            else:
                return -1
        allSetupServObjs.sort(smpPrioritet)
        for service in allSetupServObjs:
            if not service.stop():
                return False
        return True

