# -*- 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 agid
from xivo_agid import call_rights
from xivo_agid import dialplan_variables

logger = logging.getLogger(__name__)

MDS_CONFIGREGISTRAR_COLNAME = "linefeatures.configregistrar"
MDS_CONFIGREGISTRARIP_COLNAME = "mediaserver.voip_ip"
MDS_NETIFACE_ADDRESS_COLNAME = "netiface.address"
MDS_TRUNK_SECRET_COLNAME = "usersip.secret"


def _xds_routing(agi, cursor, args):
    dstnum = xivo_base_ext = agi.get_variable(dialplan_variables.BASE_EXTEN)
    srcnum = agi.get_variable(dialplan_variables.SRCNUM)
    sip_domain = agi.get_variable(dialplan_variables.SIPDOMAIN)

    line_registrar, media_server_ip = _get_mds_address(dstnum, cursor)
    local_line_registrar, _ = _get_mds_address(srcnum, cursor)

    if (not media_server_ip) and (line_registrar == 'default'):
        media_server_ip = _get_mds_main_address(cursor)

    if not (sip_domain == media_server_ip):
        secret = _get_mds_from_peer_secret(local_line_registrar, cursor)
        agi.set_variable(dialplan_variables.XDS_FROMPEER, local_line_registrar)
        agi.set_variable(dialplan_variables.XDS_CALLEDNUMBER, xivo_base_ext)
        agi.set_variable(dialplan_variables.XDS_FROMPEERSECRET, secret)
        agi.set_variable(dialplan_variables.XDS_DST_IP, media_server_ip)


def _get_mds_address(dstnum, cursor):
    cursor.query("SELECT ${columns} FROM linefeatures "
                 "LEFT JOIN mediaserver "
                 "ON linefeatures.configregistrar = mediaserver.name "
                 "WHERE linefeatures.number = %s",
                 (MDS_CONFIGREGISTRAR_COLNAME, MDS_CONFIGREGISTRARIP_COLNAME,),
                 (dstnum,))
    res = cursor.fetchone()
    return res[MDS_CONFIGREGISTRAR_COLNAME], res[MDS_CONFIGREGISTRARIP_COLNAME]


def _get_mds_from_peer_secret(name, cursor):
    cursor.query("SELECT ${columns} FROM usersip "
                 "WHERE name = %s",
                 (MDS_TRUNK_SECRET_COLNAME,),
                 (name,))
    res = cursor.fetchone()
    return res[MDS_TRUNK_SECRET_COLNAME]


def _get_mds_main_address(cursor):
    cursor.query("SELECT ${columns} FROM netiface "
                 "WHERE networktype = 'voip'",
                 (MDS_NETIFACE_ADDRESS_COLNAME,), )
    res = cursor.fetchone()
    return res[MDS_NETIFACE_ADDRESS_COLNAME]


def xds_routing(agi, cursor, args):
    try:
        _xds_routing(agi, cursor, args)
    except call_rights.RuleAppliedException:
        return


agid.register(xds_routing)
