# -*- 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/>
from builtins import object
import requests
import logging

logger = logging.getLogger(__name__)

BASE_URL = 'http://%s:%s'
SERVICES_URL = 'configmgt/api/2.0/users/%s/services'


class UserServices(object):

    def __init__(self, agi):
        self._agi = agi
        port = self._agi.config['configmgt']['port']
        host = self._agi.config['configmgt']['host']
        self._base_url = BASE_URL % (host, port)

    def get_user_services(self, user_id):
        endpoint_url = (SERVICES_URL % user_id)
        token = self._agi.config['configmgt']['token']
        try:
            response = requests.get('%s/%s' % (self._base_url, endpoint_url),
                                    headers={
                                        'Accept': 'application/json',
                                        'X-Auth-Token': token},
                                    timeout=1.25)
        except Exception as e:
            logger.error('Error during getting forwards: %s', e)
            return {'busy': {'enabled': False, 'destination': None},
                    'noanswer': {'enabled': False, 'destination': None},
                    'unconditional': {'enabled': False, 'destination': None}}
        else:
            if response.status_code == 200:
                return response.json()
            else:
                self._agi.verbose('Error requesting the webservice: %s' % response.text)
                return None

    def set_user_services(self, user_id, payload):
        endpoint_url = (SERVICES_URL % user_id)
        token = self._agi.config['configmgt']['token']
        try:
            response = requests.put('%s/%s' % (self._base_url, endpoint_url),
                                    headers={
                                        'Accept': 'application/json',
                                        'X-Auth-Token': token},
                                    json=payload,
                                    timeout=1.25)
        except Exception as e:
            logger.error('Error during setting forwards: %s', e)
            raise e
        else:
            if response.status_code == 200:
                return payload
            else:
                self._agi.verbose('Error requesting the webservice: %s' % response.text)
                return None
