# -*- 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 objects
from xivo_agid import agid, dialplan_variables
from xivo_agid.handlers.userfeatures import UserFeatures

logger = logging.getLogger(__name__)


def _set_line(dstid):
    if dstid:
        try:
            line = objects.Line(int(dstid))
        except (ValueError, LookupError), e:
            raise Exception('Unable to get line for destination: %s. %s' % (dstid, e))
        else:
            return line


def _set_xivo_line_context(agi, line):
    context = line.context
    agi.set_variable('XIVO_LINE_CONTEXT', context)


def _user_set_line_context(agi, userfeatures_handler):
    dstid = agi.get_variable(dialplan_variables.DESTINATION_ID)
    line = _set_line(dstid)

    userfeatures_handler._dstid = dstid
    userfeatures_handler._line = line
    userfeatures_handler._set_user()

    _set_xivo_line_context(agi, line)


def user_set_line_context(agi, cursor, args):
    userfeatures_handler = UserFeatures(agi, cursor, args)
    try:
        _user_set_line_context(agi, userfeatures_handler)
    except Exception, e:
        logger.error('Error during set line context: %s', e)
        agi.dp_break(e)


agid.register(user_set_line_context)
