# -*- coding: utf-8 -*-

# Copyright (C) 2020 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 objects

logger = logging.getLogger(__name__)


def get_exten_from_userid(agi, cursor, args):
    userid = args[0] if args and len(args) >= 1 else None

    billnum = ''
    if userid:
        try:
            line = objects.Line(int(userid))
        except Exception as e:
            agi.verbose("Error: Could not retrieve line for userid %s: %s" % (userid, e))
        else:
            if line.number:
                billnum = line.number
                agi.verbose("Info: Line retrieved for userid %s has number %s: setting billnum to %s" % (
                userid, line.number, billnum))
            else:
                agi.verbose("Warn: Line has no number for userid %s: cannot set billnum" % userid)
    else:
        agi.verbose("Error: No userid given, cannot set billnum")

    agi.set_variable('XIVO_BILLNUM', billnum)


agid.register(get_exten_from_userid)
