#!/usr/bin/python3
# -*- coding: UTF-8 -*-
# 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/>.


__version__ = '$Revision$'
__date__ = '$Date$'
__copyright__ = 'Copyright (C) 2014-2017 Avencall'
__author__ = 'AV'

import configparser
import json
import logging
import sys
import traceback

import requests
from xivo.agi import AGI

agi = AGI()

xuc_config = configparser.ConfigParser()
xuc_config.readfp(open('/etc/xivo-xuc.conf'))
XUC_SERVER_IP = xuc_config.get('XUC', 'XUC_SERVER_IP')
XUC_SERVER_PORT = xuc_config.get('XUC', 'XUC_SERVER_PORT')
XUC_SERVER = XUC_SERVER_IP + ':' + XUC_SERVER_PORT

TogglePauseURL = "http://" + XUC_SERVER + "/xuc/api/1.0/togglePause/"
AgentLoginURL = "http://" + XUC_SERVER + "/xuc/api/1.0/agentLogin/"
AgentLogoutURL = "http://" + XUC_SERVER + "/xuc/api/1.0/agentLogout/"

# User configuration
DEBUG_MODE = False
LOGFILE = '/var/log/xivo-xuc-agent-webservices.log'
# timeout of the tcp connection to the webserver (seconds)
CONNECTION_TIMEOUT = 5

# Factory configuration
URL_HEADERS = {'User-Agent': 'XiVO Webservice AGI'}

logger = logging.getLogger()


class Syslogger(object):

    def write(self, data):
        global logger
        logger.error(data)


def init_logging(debug_mode):
    if debug_mode:
        logger.setLevel(logging.DEBUG)
    else:
        logger.setLevel(logging.INFO)

    logfilehandler = logging.FileHandler(LOGFILE)

    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    logfilehandler.setFormatter(formatter)
    logger.addHandler(logfilehandler)

    syslogger = Syslogger()
    sys.stderr = syslogger


def logAgiFile(message, error=False):
    agi.verbose(message)
    if error == False:
        logger.info(message)
    else:
        logger.error(message)


def send_request(url, customHeaders, params):
    try:
        result = requests.post(url,
                               headers=customHeaders,
                               data=json.dumps(params),
                               timeout=CONNECTION_TIMEOUT)
        agi.verbose("Request sent to server")

    except requests.exceptions.ConnectionError:
        logAgiFile("Server XUC refused connection")

    except requests.exceptions.Timeout:
        logAgiFile("Timeout when connecting to the XUC server.")

    except:
        logAgiFile("Unknown problem during connection to the XUC server.")
        exc_type, exc_value, exc_traceback = sys.exc_info()
        logger.debug(repr(traceback.format_exception(exc_type, exc_value,
                                                     exc_traceback)))
    finally:
        agi.set_variable("XIVO_XUCWS_STATUS_CODE", str(result.status_code))
        agi.set_variable("XIVO_XUCWS_CONTENT", str(result.content))


def toggle_pause(phonenumber):
    params = {'phoneNumber': phonenumber}
    headers = {'content-type': 'application/json'}
    logAgiFile("Toggle Pause request for agent at phone: " + str(phonenumber))
    send_request(TogglePauseURL, headers, params)


def log_agent(phonenumber, agentnumber):
    params = {'agentphonenumber': phonenumber, 'agentnumber': agentnumber}
    headers = {'content-type': 'application/json'}
    logAgiFile("Agent login request for agentnumber: " + str(agentnumber) + " at phone: " + str(phonenumber))
    send_request(AgentLoginURL, headers, params)


def logout_agent(phonenumber, agentnumber):
    params = {'agentphonenumber': phonenumber, 'agentnumber': agentnumber}
    headers = {'content-type': 'application/json'}
    logAgiFile("Agent logout request for agentnumber: " + str(agentnumber) + " at phone: " + str(phonenumber))
    send_request(AgentLogoutURL, headers, params)


def main():
    agi.verbose('---------------------------------------------------')
    init_logging(DEBUG_MODE)

    if (len(XUC_SERVER) <= 0):
        logAgiFile('XUC address is not defined, the agent login/pause can\'t be used')
        logAgiFile('Please configure the address in the /etc/xivo-xuc.conf file')
        sys.exit(2)

    try:
        if len(sys.argv) < 2:
            logAgiFile("Wrong number of arguments", error=True)
            sys.exit(1)
        agi.verbose('Request: ' + sys.argv[1])
        if sys.argv[1] == 'togglePause':
            toggle_pause(sys.argv[2])
        elif sys.argv[1] == 'agentLogin':
            if len(sys.argv) < 3:
                logAgiFile('Wrong number of arguments', error=True)
                sys.exit(1)
            log_agent(sys.argv[2], sys.argv[3])
        elif sys.argv[1] == 'agentLogout':
            logout_agent(sys.argv[2], sys.argv[3])
        else:
            logAgiFile('Undefined request', error=True)
    except Exception:
        exc_type, exc_value, exc_traceback = sys.exc_info()
        logger.error(repr(traceback.format_exception(exc_type, exc_value,
                                                     exc_traceback)))
        sys.exit(1)

    sys.exit(1)


if __name__ == '__main__':
    main()
