#!/usr/bin/python3
# -*- coding: UTF-8 -*-
# Copyright (C) 2012  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, write to the Free Software Foundation, Inc.,


import configparser

import requests
from xivo.agi import AGI


def _is_recording_disabled(src_num, agi):
    config = configparser.ConfigParser()
    config.readfp(open('/etc/xivocc-recording.conf'))
    recording_url = config.get('recording-server', 'RECORDING_SERVER')
    result = requests.get('http://%s:9400/recording/filtered_internal_numbers/%s' % (recording_url, src_num),
                          verify=False,
                          headers={'Accept': 'application/json'}, timeout=2)
    if result.status_code == 404:
        return False
    elif result.status_code == 200:
        return True
    else:
        agi.verbose('Error requesting the web service : %s' % result.text)
        return False


def main(agi):
    src_num = agi.get_variable('XIVO_SRCNUM')
    if _is_recording_disabled(src_num, agi):
        agi.set_variable('DO_RECORD', 'false')
    else:
        agi.set_variable('DO_RECORD', 'true')


if __name__ == '__main__':
    main(AGI())
