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

from xivo_agid import agid, dialplan_variables

logger = logging.getLogger(__name__)

MDS_CONFIGREGISTRAR_COLNAME = "mediaserver.name"


def _get_dialplan_variables(cursor, agi):
    dstnum = agi.get_variable(dialplan_variables.EXTEN)
    exten_context = agi.get_variable(dialplan_variables.BASE_CONTEXT)
    xds_context = agi.get_variable(dialplan_variables.XDS_CONTEXT)

    context = xds_context if xds_context else exten_context

    xds_peer = _get_mds_address(dstnum, context, cursor)

    return {
        'xds_peer': xds_peer,
        'xds_called_number': dstnum
    }


def _set_dialplan_variables(agi, dial_string_variables):
    agi.set_variable(dialplan_variables.XDS_PEER, dial_string_variables['xds_peer'])
    agi.set_variable(dialplan_variables.XDS_CALLEDNUMBER, dial_string_variables['xds_called_number'])


def _get_mds_address(dstnum, exten_context, cursor):
    cursor.query("SELECT ${columns} FROM mediaserver "
                 "LEFT JOIN linefeatures "
                 "ON linefeatures.configregistrar = mediaserver.name "
                 "LEFT JOIN groupfeatures "
                 "ON groupfeatures.mediaserverid = mediaserver.id "
                 "WHERE (linefeatures.number = %(dstnum)s AND linefeatures.context = %(exten_context)s) "
                 "OR (groupfeatures.number = %(dstnum)s AND groupfeatures.context = %(exten_context)s)",
                 (MDS_CONFIGREGISTRAR_COLNAME,),
                 {'dstnum': dstnum, 'exten_context': exten_context})
    try:
        res = cursor.fetchone()
        config_registrar = res[MDS_CONFIGREGISTRAR_COLNAME]
        if config_registrar is None:
            raise LookupError('Registrar: %s' % (config_registrar))
    except Exception, e:
        raise LookupError('Unable to get mds for destination: %s. %s' % (dstnum, e))
    else:
        return config_registrar


def _xds_routing(agi, cursor, args):
    dial_string_variables = _get_dialplan_variables(cursor, agi)
    _set_dialplan_variables(agi, dial_string_variables)


def xds_routing(agi, cursor, args):
    try:
        _xds_routing(agi, cursor, args)
    except Exception, e:
        logger.error('Error during xds routing: %s', e)
        agi.dp_break(e)


agid.register(xds_routing)
