# -*- 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/>

from __future__ import print_function
from xivo_confgen.hints import adaptor as hint_adaptor
from xivo_dao.resources.func_key import hint_dao

from xivo_confgen.hints.adaptor import UserAdaptor

from xivo_confgen.generators.sip_user import key_found_and_equal


class HintGenerator(object):
    DIALPLAN = "exten = {extension},hint,{hint}"
    HINT_UA = "{}&{}_w"

    @classmethod
    def build(cls):
        return cls([hint_adaptor.UserAdaptor(hint_dao),
                    hint_adaptor.ConferenceAdaptor(hint_dao),
                    hint_adaptor.ServiceAdaptor(hint_dao),
                    hint_adaptor.ForwardAdaptor(hint_dao),
                    hint_adaptor.AgentAdaptor(hint_dao),
                    hint_adaptor.BSFilterAdaptor(hint_dao),
                    hint_adaptor.CustomAdaptor(hint_dao)])

    def __init__(self, adaptors):
        self.adaptors = adaptors

    def generate(self, context, systemname):
        existing = set()
        for adaptor in self.adaptors:
            user_hints = adaptor.generate(context)
            for user_hint in user_hints:
                extension = user_hint[0]
                hint = user_hint[1]
                mds = user_hint[2]
                hint = self.hint_format(adaptor, hint, user_hint)
                if extension not in existing and (mds == systemname or mds is None):
                    yield self.DIALPLAN.format(extension=extension,
                                               hint=hint)
                    existing.add(extension)

    def hint_format(self, adaptor, hint, user_hint):
        return self.HINT_UA.format(hint, hint) if (isinstance(adaptor, UserAdaptor) and user_hint[3] is not None and key_found_and_equal('webrtc', 'ua', user_hint[3])) else hint
