# -*- coding: utf-8 -*-
"""
This provides the REST classes used to access the User Service.

To launch the server for testing, go to Service directory

    $ cd /home/vagrant/src/bookingsys/pp-latchpony-restservice/Service

and start the server on port 16804 with

    $ pserve --reload development.ini

"""
import json
import logging
from urlparse import urljoin

import requests

#from pp.auth import pwtools
from pp.latchpony.validate import error
from pp.latchpony.client import gymkhana


def get_log(extra=None):
    log_name = "{}.{}".format(__name__, extra) if extra else __name__
    return logging.getLogger(log_name)


class LatchPonyService(object):
    """This provides an interface to the REST service for dealing with
    user operations.
    """
    DUMP = "/poniverse/dump/"

    LOAD = "/poniverse/load/"

    def __init__(self, uri='http://localhost:16804'):
        """Set the URI of the LatchPonyService.

        :param uri: The base address of the User Service server.

        """
        self.log = get_log('LatchPonyService')
        self.base_uri = uri
        self.gymkhana = gymkhana.Gymkhana(uri)

    def ping(self):
        """Recover the User Service status page.

        This will raise a connection error or it will return successfully.

        :returns: service status dict.

        """
        response = requests.get(self.base_uri)
        response.raise_for_status()
        return json.loads(response.content)

    def dump(self):
        """Used in testing to dump the entire latchpony universe.

        :returns: A dict.

        This has the form::

            dumped = { ?? }

        """
        uri = urljoin(self.base_uri, self.DUMP)
        self.log.debug("dump: uri <{}>".format(uri))

        res = requests.get(uri)

        rc = json.loads(res.content)

        if res.status_code not in [200]:
            raise error.CommunicationError(rc['message'])

        return rc

    def load(self, data):
        """Used in testing to load an entire latchpony universe.

        :param data: See the return of a call to dump().

        """
        uri = urljoin(self.base_uri, self.LOAD)
        self.log.debug("load: uri <{}>".format(uri))

        data = json.dumps(data)
        res = requests.post(uri, data=data)

        rc = json.loads(res.content)

        if res.status_code not in [200]:
            raise error.CommunicationError(rc['message'])
