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

# Copyright (C) 2018 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 xivo_agid import dialplan_variables
from xivo_agid import objects

from xivo_agid import agid

logger = logging.getLogger(__name__)


def _get_ua_variables(agi, cursor, userId):
    _set_enablednd(agi, cursor, userId)
    line = objects.Line(int(userId))    
    interface = _build_interface_from_line(agi, line)
    agi.set_variable(dialplan_variables.INTERFACE, interface)
    if line and line.webrtc == 'ua':
        agi.set_variable('XIVO_UA_INTERFACE_WEBRTC', '%s_w' % interface)

def _build_interface_from_line(agi, line):
    sip_driver = agi.get_variable(dialplan_variables.SIPDRIVER)    
    protocol = line.protocol
    if protocol.lower() == 'custom':
        interface = line.name
    elif sip_driver == 'PJSIP':
        interface = '%s/%s' % (sip_driver, line.name)
    else:
        interface = '%s/%s' % (protocol, line.name)
    return interface

def _set_enablednd(agi, cursor, userId):
    feature = objects.ExtenFeatures(agi, cursor)
    user = objects.User(agi, cursor, int(userId))
    if feature.enablednd :
        enablednd = user.enablednd
    else:
        enablednd = 0
    agi.set_variable('XIVO_ENABLEDND', enablednd)

def get_ua_variables(agi, cursor, args):
    try:
        _get_ua_variables(agi, cursor, args[0])
    except Exception as e:
        logger.error('Error during get ua value: %s', e)
        agi.dp_break(e)        


agid.register(get_ua_variables)
