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

from builtins import next
from builtins import object
import os

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


class SipUserGenerator(object):
    EXCLUDE_OPTIONS = ('name',
                       'protocol',
                       'category',
                       'disallow',
                       'regseconds',
                       'lastms',
                       'name',
                       'fullcontact',
                       'ipaddr')

    WEBRTC_KEY = 'webrtc'
    WEBRTC_TRANSPORT_UDP = 'transport = udp '
    WEBRTC_TRANSPORT_WS = 'transport = ws'
    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',
        'sendrpid = no',
        'rtptimeout = 20',
        'rtcp_mux = yes',
        'videosupport = yes'
    ]
    WEBRTC_CODEC_DEFAULT = [
        'disallow = all',
        'allow = opus,alaw,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
        self.systemname = os.getenv('MDS_NAME', 'default')

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

    def format_row(self, row, ccss_options):
        usersip_name = row.UserSIP.name

        usersip_options = ['setvar = CHANNEL(hangup_handler_push)=hangup_handlers,userevent,1']

        for line in self.format_user_options(row):
            usersip_options.append(line)
        for line in self.format_options(iter(ccss_options.items())):
            usersip_options.append(line)

        options = row.UserSIP.all_options(self.EXCLUDE_OPTIONS)
        for line in self.format_allow_options(options):
            usersip_options.append(line)
        for line in self.format_options(options):
            if not line.startswith(self.WEBRTC_KEY):
                usersip_options.append(line)

        if 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:
                    usersip_options.append(line)
                if not self.codec_customized_on_line(options):
                    for line in self.WEBRTC_CODEC_DEFAULT:
                        usersip_options.append(line)
                self._add_transport_type(usersip_options)

        # Create peer section with option
        yield '[{}]'.format(usersip_name)
        for line in usersip_options:
            yield line
        yield ''

        # Generate additional peer section with webrtc option for UA line
        if key_found_and_equal(self.WEBRTC_KEY, 'ua', options):
            self._add_transport_type(usersip_options)
            yield '[{}_w]'.format(usersip_name)
            for line in usersip_options:
                yield line
            for line in self.WEBRTC_OPTIONS:
                yield line
            if not self.codec_customized_on_line(options):
                for line in self.WEBRTC_CODEC_DEFAULT:
                    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 codec_customized_on_line(self, options):
        return self.key_found('allow', options)

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

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

    def _add_transport_type(self, usersip_options):
        if self._is_stun_address_defined():
            usersip_options.append(self.WEBRTC_TRANSPORT_UDP)
        else:
            usersip_options.append(self.WEBRTC_TRANSPORT_WS)

    def _is_stun_address_defined(self):
        data_general = self.sip_dao.find_sip_general_settings(self.systemname)
        stun = next((item for item in data_general if item["var_name"] == "stunaddr" and item["var_val"] is not None), None)
        return bool(stun)
