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

# Copyright (C) 2021 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 json
from re import search

import requests

from xivo_agid import agid

BASE_URL = 'http://%s:%s'
TRUNK_JITSI = 'xivo-jitsi'


def strip_prefix(number, prefix):
    if number.startswith(prefix):
        return number[len(prefix):]
    return number


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 get_meeting_room_by_number(agi, number):
    prefix = "**"
    regexp = "\*{2}\d*"

    if not search(regexp, number):
        agi.dp_break('Error number is not in required format: %s' % number)

    number = strip_prefix(number, prefix)
    configmgt_ws = 'configmgt/api/2.0/meetingrooms/number/%s' % number

    try:
        response = get_request(agi, configmgt_ws)
    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:
            res = json.loads(response.content)
            set_meeting_room_trunk(agi)
            set_meeting_room_pin(agi, res)
            set_meeting_room_name(agi, res)
        elif response.status_code == 404:
            agi.set_variable('XIVO_MEETING_ROOM', '')
        else:
            agi.dp_break('Error requesting the webservice: %s' % response.text)


def get_meeting_room_by_id(agi, meeting_room_id):
    configmgt_ws = 'configmgt/api/2.0/meetingrooms/static/%s' % meeting_room_id
    try:
        response = get_request(agi, configmgt_ws)
    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:
            res = json.loads(response.content)
            set_meeting_room_trunk(agi)
            set_meeting_room_pin(agi, res)
            set_meeting_room_name(agi, res)
        else:
            agi.dp_break('Error requesting the webservice: %s' % response.text)


def set_meeting_room_name(agi, res):
    agi.set_variable('XIVO_MEETING_ROOM', res['uuid'])
    agi.set_variable('XIVO_MEETING_ROOM_DISPLAY_NAME', res['displayName'])


def set_meeting_room_trunk(agi):
    jitsi_peer = agi.get_variable('SIPPEER(%s)' % TRUNK_JITSI)
    if jitsi_peer:
        agi.set_variable('XIVO_MEETING_ROOM_TRUNK', TRUNK_JITSI)


def set_meeting_room_pin(agi, res):
    if "userPin" in res:
        agi.set_variable('XIVO_MEETING_ROOM_PIN', res['userPin'])


def incoming_meetingroom_set_features(agi, cursor, args):
    meeting_room_id = agi.get_variable('XIVO_DST_ROOM_ID')
    if not meeting_room_id:
        meeting_room_number = agi.get_variable('XIVO_DST_ROOM_NUM')
        get_meeting_room_by_number(agi, meeting_room_number)
    else:
        get_meeting_room_by_id(agi, meeting_room_id)


agid.register(incoming_meetingroom_set_features)
   