# -*- coding: UTF-8 -*-

# Copyright (C) 2015-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, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

from __future__ import unicode_literals


class SipUserGenerator(object):

    EXCLUDE_OPTIONS = ('name',
                       'protocol',
                       'category',
                       'disallow',
                       'regseconds',
                       'lastms',
                       'name',
                       'fullcontact',
                       'ipaddr')

    WEBRTC_KEY = 'webrtc'
    WEBRTC_OPTIONS = [
        'avpf = yes',
        'call-limit = 2',
        'encryption = yes',
        'force_avp = yes',
        'icesupport= yes',
        'dtlsenable = yes',
        'dtlsverify = no',
        'dtlscertfile = /etc/asterisk/keys/asterisk.pem',
        'dtlsprivatekey = /etc/asterisk/keys/asterisk.pem',
        'dtlssetup = actpass',
        'transport = ws',
        'sendrpid = no',
        'rtptimeout = 20',
        'rtcp_mux = yes',
        'videosupport = yes',
        'allow = ulaw,vp8'
    ]

    def __init__(self, sip_dao, line_dao, nova_compatibility=False):
        self.sip_dao = sip_dao
        self.line_dao = line_dao
        self._nova_compatibility = nova_compatibility

    def generate(self, ccss_options):
        for row in self.sip_dao.find_sip_user_settings():
            for line in self.format_row(row, ccss_options):
                yield line

    def format_row(self, row, ccss_options):
        yield '[{}]'.format(row.UserSIP.name)
        yield 'setvar = CHANNEL(hangup_handler_push)=hangup_handlers,userevent,1'

        for line in self.format_user_options(row):
            yield line
        for line in self.format_options(ccss_options.iteritems()):
            yield line

        options = row.UserSIP.all_options(self.EXCLUDE_OPTIONS)
        for line in self.format_allow_options(options):
            yield line
        for line in self.format_options(options):
            if not line.startswith(self.WEBRTC_KEY):
                yield line
        if self.key_found_and_equal(self.WEBRTC_KEY, 'yes', options):
            if not self.line_dao.device_exists_for_sip_id(row.UserSIP.id):
                for line in self.WEBRTC_OPTIONS:
                    yield line

        yield ''

    def format_user_options(self, row):
        if row.context:
            yield 'setvar = TRANSFER_CONTEXT={}'.format(row.context)
        if row.number and row.context:
            yield 'setvar = PICKUPMARK={}%{}'.format(row.number, row.context)
        if row.user_id:
            yield 'setvar = XIVO_USERID={}'.format(row.user_id)
        if row.uuid:
            yield 'setvar = XIVO_USERUUID={}'.format(row.uuid)
        if row.namedpickupgroup:
            yield 'namedpickupgroup = {}'.format(row.namedpickupgroup)
        if row.namedcallgroup:
            yield 'namedcallgroup = {}'.format(row.namedcallgroup)
        if row.mohsuggest:
            yield 'mohsuggest = {}'.format(row.mohsuggest)
        if row.mailbox:
            yield 'mailbox = {}'.format(row.mailbox)
        if row.UserSIP.callerid:
            yield 'description = {}'.format(row.UserSIP.callerid)
        if self._nova_compatibility and row.number:
            yield 'accountcode = {}'.format(row.number)

    def key_found(self, key, options):
        return key in (option_name for option_name, _ in options)

    def key_found_and_equal(self, key, value, options):
        return [key, value] in ([option_name, option_value] for option_name, option_value in options)

    def format_allow_options(self, options):
        if self.key_found('allow', options):
            yield 'disallow = all'

    def format_options(self, options):
        for name, value in options:
            yield '{} = {}'.format(name, value)
