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

# Copyright (C) 2014-2015 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 collections import namedtuple

from xivo_dao.resources.utils.searchers import Searcher, SearcherFuzzy, SearcherCombinedNG

logger = logging.getLogger(__name__)

SearchResult = namedtuple('SearchResult', ['total', 'items'])


class SearchSystem(object):
    searchers = (Searcher,)

    def __init__(self, config):
        self.config = config
        self._searchers = list([_(config) for _ in self.searchers])

    def search(self, session, parameters=None):
        query = session.query(self.config.table)
        return self.search_from_query(query, parameters)

    def search_from_query(self, query, parameters=None):
        results = list()
        for searcher in self._searchers:
            results = searcher.search_from_query(query, parameters)
            if len(results[0]) > 0:
                logger.debug('%s was used to supply %s search results.', searcher.id_text, len(results[0]))
                break
        else:
            logger.debug('All searches returned empty result.')
        return results


class SearchSystemNG(SearchSystem):
    searchers = (SearcherCombinedNG, SearcherFuzzy)

    def __init__(self, config):
        super(SearchSystemNG, self).__init__(config)
        self._lister = self._searchers[0]

    def search(self, session, parameters=None):
        query = session.query(*self.config.columns.values())
        return self.search_from_query(query, parameters)

    def search_from_query(self, query, parameters=None):
        ids = parameters.get('unique_ids')
        if ids:
            return self._lister.list_from_query(query, ids)

        return super(SearchSystemNG, self).search_from_query(query, parameters)

    def list(self, session, unique_ids):
        query = session.query(*self.config.columns.values())
        return self.list_from_query(query, unique_ids)

    def list_from_query(self, query, unique_ids):
        return self._lister.list_from_query(query, unique_ids)
