# -*- coding: utf-8 -*-
# Copyright 2006-2019 The Wazo Authors  (see the AUTHORS file)
# SPDX-License-Identifier: GPL-3.0-or-later

import logging

from wazo_agid import agid, objects

logger = logging.getLogger(__name__)


def phone_get_features(agi, cursor, args):
    userid = agi.get_variable('XIVO_USERID')

    try:
        user = objects.User(agi, cursor, int(userid))
    except (ValueError, LookupError) as e:
        agi.dp_break(str(e))

    _set_current_forwards(agi, user.id)

    for service in objects.ExtenFeatures.FEATURES['services']:
        enable = bool(getattr(user, service[1], 0))
        agi.set_variable("XIVO_%s" % service[1].upper(), int(enable))


def _set_current_forwards(agi, user_id):
    forwards = _get_forwards(agi, user_id)
    busy_forward = forwards['busy']
    agi.set_variable('XIVO_ENABLEBUSY', _extract_and_format_enabled(busy_forward))
    agi.set_variable('XIVO_DESTBUSY', _extract_and_format_destination(busy_forward))
    noanswer_forward = forwards['noanswer']
    agi.set_variable('XIVO_ENABLERNA', _extract_and_format_enabled(noanswer_forward))
    agi.set_variable('XIVO_DESTRNA', _extract_and_format_destination(noanswer_forward))
    unconditional_forward = forwards['unconditional']
    agi.set_variable('XIVO_ENABLEUNC', _extract_and_format_enabled(unconditional_forward))
    agi.set_variable('XIVO_DESTUNC', _extract_and_format_destination(unconditional_forward))


def _extract_and_format_enabled(forward):
    return int(forward['enabled'])


def _extract_and_format_destination(forward):
    return forward['destination'] if forward['destination'] is not None else ''


def _get_forwards(agi, user_id):
    try:
        confd_client = agi.config['confd']['client']
        return confd_client.users(user_id).list_forwards()
    except Exception as e:
        logger.error('Error during getting forwards: %s', e)
        return {'busy': {'enabled': False, 'destination': None},
                'noanswer': {'enabled': False, 'destination': None},
                'unconditional': {'enabled': False, 'destination': None}}


agid.register(phone_get_features)
