#!/usr/bin/env python
# -*- coding: utf-8 -*-
# $Id: Local.py 9439 2015-09-25 08:01:30Z Eric $
#
# Copyright (c) 2015 Nuwa Information Co., Ltd, All Rights Reserved.
#
# Licensed under the Proprietary License,
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at our web site.
#
# See the License for the specific language governing permissions and
# limitations under the License.
#
# $Author: Eric $ (last)
# $Date: 2015-09-25 16:01:30 +0800 (Fri, 25 Sep 2015) $
# $Revision: 9439 $

import os

from Iuppiter.Util import preferredSort, OrderedDict, SafeConfigParser

from Iuno.cloud.backend import BaseBackend

class Backend(BaseBackend):

    def __init__(self, context=None, config=None):
        super(Backend, self).__init__(context, config)

        self.domains = OrderedDict()
        self.windows = []

        defaultConfig = self._getDefaultConfig()

        if context:
            serviceKey = self.__class__.__module__.split('.')[-3].upper()

            hostKey = 'IUNO_CLOUD_%s_BACKEND_HOST' % serviceKey
            if hostKey in context:
                domain = context[hostKey]
                self.domains[domain] = defaultConfig.copy()
                # Read configuration from settings.
                for key in defaultConfig:
                    if key in context:
                        self.domains[domain][key] = context[key]
                    if config and key in config:
                        self.domains[domain][key] = config[key]

            configKey = 'IUNO_CLOUD_%s_LOCAL_CONFIG' % serviceKey
            if configKey in context:
                configFile = SafeConfigParser()
                configFile.read(context[configKey])
                # Read configuration from file.
                for domain in configFile.sections():
                    self.domains[domain] = defaultConfig.copy()
                    for key in defaultConfig:
                        if configFile.has_option(domain, key):
                            self.domains[domain][key] = \
                                self._cast(key, configFile.get(domain, key))

        if not self.domains:
            self.domains['localhost'] = defaultConfig.copy()

        for domain in self.domains.keys():
            hostOS = self.domains[domain]['HOST_OS'].lower()
            if hostOS.startswith('win'):
                self.windows.append(domain)

        if 'localhost' in self.domains or '127.0.0.1' in self.domains:
            # Detect OS.
            if os.name == 'nt':
                if 'localhost' not in self.windows:
                    self.windows.append('localhost')
                if '127.0.0.1' not in self.windows:
                    self.windows.append('127.0.0.1')

    def _getDefaultConfig(self):
        """
        Get default configuration for derived backend.

        @return Default configuration dictionary.
        """
        return {}

    def _cast(self, key, value):
        """
        Cast value from configuration file to proper type.

        @param key Configuration key.
        @param value Configuration value (string).
        @return Casted value.
        """
        return value

    def _checkMonit(self, host, services):
        if host in self.windows:
            return True # Windows don't have monit to check.
        else:
            return super(Backend, self)._checkMonit(host, services)

    def getDomains(self, preferred=None):
        if preferred:
            domains = preferredSort(list(self.domains.keys()), preferred,
                                    inPlace=False)
        else:
            domains = list(self.domains.keys())

        self.logger.info('INSTANCES: %s' % str(domains))
        return domains
