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

from xivo_agid import dialplan_variables
from xivo_agid import objects

from xivo_agid import agid

logger = logging.getLogger(__name__)


def _groupmember_set_features(agi, cursor, userId):
    user = objects.User(agi, cursor, int(userId))
    line = objects.Line(int(userId))    
    interface = _build_interface_from_line(agi, line)
    _set_enablednd(agi, cursor, user)
    _set_interface(agi, interface)
    _set_ua(agi,line, interface)
    _set_mobile_app(agi, line, user.userpreferences, user.mobile_push_token)
    _set_queue_call_options(agi)
    _set_group_call_options(agi)
    

def _set_interface(agi, interface):
    agi.set_variable(dialplan_variables.INTERFACE, 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, user):
    feature = objects.ExtenFeatures(agi, cursor)
    if feature.enablednd :
        enablednd = user.enablednd
    else:
        enablednd = 0
    agi.set_variable('XIVO_ENABLEDND', enablednd)

def _set_queue_call_options(agi):
    queue_options = agi.get_variable('XIVO_QUEUEOPTIONS')
    queue_call_options = extract_call_options(queue_options)
    agi.set_variable('XIVO_QUEUECALLOPTIONS', queue_call_options)

def _set_group_call_options(agi):
    group_options = agi.get_variable('XIVO_GROUPOPTIONS')
    group_call_options = extract_call_options(group_options)
    agi.set_variable('XIVO_GROUPCALLOPTIONS', group_call_options)

def extract_call_options(options):
    options = re.sub(r'\(.*?\)', '', options)
    authorized_options = ['h', 'i', 't', 'w', 'x', 'k']
    call_options = ''
    for option in options:
        if option in authorized_options:
            call_options += option
    return call_options

def _set_ua(agi, line, interface):
    if line and line.webrtc == 'ua':
        agi.set_variable('XIVO_UA_INTERFACE_WEBRTC', '%s_w' % interface)        

def _set_mobile_app(agi, line, userpreferences, mobile_push_token):
    mobile_app = False
    if 'MOBILE_APP_INFO' in userpreferences:
        _mobile_app_info = userpreferences.get('MOBILE_APP_INFO') if userpreferences.get('MOBILE_APP_INFO') != None else ''
        _ring_device = userpreferences.get('PREFERRED_DEVICE')
        agi.set_variable(dialplan_variables.RING_DEVICE, _ring_device or '')
        if line and line.webrtc == 'yes' and _mobile_app_info is not None:
            mobile_app = True
            agi.set_variable(
            dialplan_variables.MOBILE_PUSH_TOKEN, mobile_push_token or "NOT_REGISTERED")            
    agi.set_variable(dialplan_variables.USER_HAS_MOBILE_APP, '%s' % mobile_app)    

def groupmember_set_features(agi, cursor, args):
    try:
        _groupmember_set_features(agi, cursor, args[0])
    except Exception as e:
        logger.error('Error during groupmember set features: %s', e)
        agi.dp_break(e)        


agid.register(groupmember_set_features)
