# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import json
import urllib

import requests

from core import exceptions


class OTRSClientException(exceptions.CoreException):
    pass


class OTRSClient(object):

    def __init__(self, base_url, key):
        self._base_url = base_url
        self._key = key

    def _request(self, method, params):
        response = requests.post(
            self._get_url(),
            self._pack_data(method, params))
        return response

    def _get_url(self):
        return self._base_url + urllib.urlencode({'Key': self._key})

    def _pack_data(self, method, params):
        return json.dumps({
            'jsonrpc': '2.0',
            'method': method,
            'params': params,
            'id': 0,
        })

    def get_ticket_number(self, ticket_id):
        response = self._request('ticket_get_info', {'TicketID': ticket_id})
        try:
            ticket_number = response.json()['result']['list'][0]['TicketNumber']
        except (KeyError, IndexError) as exc:
            raise OTRSClientException('Unexpected OTRS response: %s' % response.content)
        else:
            return ticket_number
