# -*- coding: utf-8 -*-
#
# Copyright (C) 2014-2016 Avencall
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>


import logging
from concurrent.futures import ALL_COMPLETED
from concurrent.futures import ThreadPoolExecutor
from concurrent.futures import wait

from xivo_dird import BaseServicePlugin
from xivo_dird import helpers

logger = logging.getLogger(__name__)


class LookupServicePlugin(BaseServicePlugin):

    def __init__(self):
        self._service = None

    def load(self, args):
        try:
            self._service = _LookupService(args['config'], args['sources'])
            return self._service
        except KeyError:
            msg = ('%s should be loaded with "config" and "sources" but received: %s'
                   % (self.__class__.__name__, ','.join(args.keys())))
            raise ValueError(msg)

    def unload(self):
        if self._service:
            self._service.stop()
            self._service = None


class _LookupService(object):

    def __init__(self, config, sources):
        self._global_config = config
        self._sources = sources
        self._executor = ThreadPoolExecutor(max_workers=10)

    def stop(self):
        self._executor.shutdown()

    def _config(self, service_name='lookup'):
        return self._global_config.get('services', {}).get(service_name, {})

    def _async_search(self, source, term, args):
        raise_stopper = helpers.RaiseStopper(return_on_raise=[])
        future = self._executor.submit(raise_stopper.execute, source.search, term, args)
        future.name = source.name
        return future

    def _source_by_profile(self, profile):
        try:
            source_names = self._config().get(profile, {})['sources']
        except KeyError:
            logger.warning('Cannot find lookup sources for profile %s', profile)
            return []
        else:
            return [self._sources[name] for name in source_names if name in self._sources]

    def _source_by_label(self, label_id):
        labels_config = self._config('lookup_by_labels').get('labels', {})
        source_names = labels_config.get(label_id, {}).get('sources', [])
        return [self._sources[name] for name in source_names if name in self._sources]

    def _timeout_by_label(self, label_id):
        labels_config = self._config('lookup_by_labels').get('labels', {})
        return labels_config.get(label_id, {}).get('timeout')

    def _get_default_sources(self):
        default_config = self._config('lookup_by_labels').get('default_sources', {})
        source_names = default_config.get('sources', [])
        sources = [self._sources[name] for name in source_names if name in self._sources]
        return sources, default_config.get('timeout')

    def _deduplicate_sources(self, sources):
        unique_sources = []
        seen_names = set()

        for source in sources:
            if source.name in seen_names:
                continue
            seen_names.add(source.name)
            unique_sources.append(source)

        return unique_sources

    def _run_sources(self, sources, term, xivo_user_uuid, args, token, timeout=None):
        futures = []

        for source in sources:
            args['token'] = token
            args['xivo_user_uuid'] = xivo_user_uuid
            futures.append(self._async_search(source, term, args))

        params = {'return_when': ALL_COMPLETED}
        if timeout is not None:
            params['timeout'] = timeout

        done, _ = wait(futures, **params)

        results = []
        for future in done:
            results.extend(future.result())

        return results

    def lookup(self, term, profile, xivo_user_uuid, args, token):
        sources = self._source_by_profile(profile)
        timeout = self._config().get(profile, {}).get('timeout')
        return self._run_sources(sources, term, xivo_user_uuid, args, token, timeout)


    def lookup_by_labels(self, term, labels, xivo_user_uuid, args, token):
        all_sources = []
        timeouts = []

        for label in labels:
            all_sources.extend(self._source_by_label(label))

            timeout = self._timeout_by_label(label)
            if timeout is not None:
                timeouts.append(timeout)

        unique_sources = self._deduplicate_sources(all_sources)
        if unique_sources:
            timeout = max(timeouts, default=None)
        else:
            unique_sources, timeout = self._get_default_sources()

        return self._run_sources(unique_sources, term, xivo_user_uuid, args, token, timeout)
