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

# Copyright (C) 2022 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 requests

from xivo_agid import agid

BASE_URL = 'http://%s:%s'
PREFERENCE_KEY_MISSED_CALLS = 'MISSED_CALLS_NB'


def get_request(agi, url):
    port = agi.config['configmgt']['port']
    host = agi.config['configmgt']['host']
    base_url = BASE_URL % (host, port)
    token = agi.config['configmgt']['token']
    res = requests.get('%s/%s' % (base_url, url),
                       headers={
                           'Accept': 'application/json',
                           'X-Auth-Token': token
                       }, timeout=1.25)
    return res

def increased_missed_calls(agi, user_id):
    url = 'configmgt/api/2.0/users/%s/new_missed_call' % user_id
    return get_request(agi, url)

def add_missed_call_for_user(agi, cursor, args):
    user_id = agi.get_variable('XIVO_USERID')
    if user_id:
        agi.verbose('Increase number of missed call for user %s', user_id)
        try:
            response = increased_missed_calls(agi, user_id)
        except requests.Timeout as e:
            agi.dp_break('Error requesting the webservice (Timeout): %s' % e)
        except Exception as e:
            agi.dp_break('Error requesting the webservice: %s' % e)
        else:
            if response.status_code != 200:
                agi.dp_break('Error requesting the webservice: %s' % response.text)
    else:
        agi.dp_break('Cannot increase the number of missed call, no user id found')

agid.register(add_missed_call_for_user)