# -*- 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_dao import user_dao, group_dao

from xivo_agid import agid

logger = logging.getLogger(__name__)


def _fwd_get_mds(agi):
    fwd_action = agi.get_variable('XIVO_FWD_ACTION')
    fwd_arg1 = agi.get_variable('XIVO_FWD_ACTIONARG1')
    mds = None
    systemname = os.getenv('MDS_NAME', 'default')

    if (fwd_action == 'user'):
        mds = user_dao.get_mds_by_user_id(fwd_arg1)
    elif (fwd_action == 'group'):
        mds = group_dao.get_mds_by_group_id(fwd_arg1)
    elif (fwd_action in ['queue', 'meetme']):
        mds = 'default'

    if mds is not None and mds != systemname:
        agi.set_variable('XDS_PEER', mds)


def fwd_get_mds(agi, cursor, args):
    try:
        _fwd_get_mds(agi)
    except Exception as e:
        logger.error('Error during fwd_get_mds: %s', e)
        agi.dp_break(e)


agid.register(fwd_get_mds)
