# -*- 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

import requests

from xivo_agid import agid


JITSI_DOMAIN = "meet.jitsi"
JITSI_TRUNK = "xivo-jitsi"
JITSI_PORT = "5280"


def get_participants(agi, meeting_room_name):
    jitsi_server_host = agi.get_variable('SIPPEER(%s)' % JITSI_TRUNK)
    if not jitsi_server_host:
        agi.verbose('Error requesting the webservice (Hostname is empty)')
        agi.execute('Goto', 'failure')
    try:
        response = requests.get(
            'http://%s:%s/room-size?room=%s&domain=%s' % (jitsi_server_host, JITSI_PORT, meeting_room_name, JITSI_DOMAIN),
            headers={
                'Accept': 'application/json'
            }, timeout=1.25)
    except requests.Timeout as e:
        agi.verbose('Error requesting the webservice (Timeout): %s' % e)
    except Exception as e:
        agi.verbose('Error requesting the webservice: %s' % e)
    else:
        if response.status_code == 200:
            res = json.loads(response.content)
            participants = res['participants']
            if participants > 0:
                agi.set_variable('XIVO_MEETING_ROOM_READY', 1)
            else:
                agi.set_variable('XIVO_MEETING_ROOM_READY', 0)
        elif response.status_code == 404:
            agi.set_variable('XIVO_MEETING_ROOM_READY', 0)
        else:
            agi.verbose('Error requesting the webservice: %s' % response.text)
            agi.execute('Goto', 'failure')


def meetingroom_availability_check(agi, cursor, args):
    meeting_room_name = agi.get_variable('XIVO_MEETING_ROOM')
    if not meeting_room_name:
        agi.dp_break('Error getting the meeting room name from the channel variable')
    agi.set_variable('XIVO_MEETING_ROOM_READY', 0)
    agi.execute('SET MUSIC ON')
    get_participants(agi, meeting_room_name)


agid.register(meetingroom_availability_check)
