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

# Copyright (C) 2021 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

import os

from xivo_dao.helpers.db_utils import session_scope

RTP_PORT_RANGE_OPTIONS = 'rtpstart = 10000\n' \
                         'rtpend = 20000'
ICE_SUPPORT = 'icesupport = yes'


class RtpConf(object):
    def __init__(self, asterisk_conf_dao, stun_enable=False, turn_enable=True):
        self.asterisk_conf_dao = asterisk_conf_dao
        self.systemname = os.getenv('MDS_NAME', 'default')
        self.stun_enable = stun_enable
        self.turn_enable = turn_enable

    def generate(self, output):
        with session_scope():
            self._generate(output)

    def _generate(self, output):
        data_general = self.asterisk_conf_dao.find_sip_general_settings(self.systemname)
        self._gen_general(data_general, output)

    def _gen_general(self, data_general, output):
        print >> output, '[general]'
        print >> output, RTP_PORT_RANGE_OPTIONS
        print >> output, ICE_SUPPORT

        for item in data_general:
            if item['var_val'] is None:
                continue
            if item['var_name'] == "stunaddr":
                if self.stun_enable:
                    print >> output, "stunaddr", "=", item['var_val']
                if self.turn_enable:
                    print >> output, "turnaddr", "=", item['var_val']
