import json
import requests


class Server(object):
    "Gets state from server and sends it to the server after change"
    def __init__(self, url_base=None, controller_id=None):
        self.url_base = url_base
        self.controller_id = controller_id

    def get_state(self):
        result = requests.get(self.full_url('state/%s') % self.controller_id)
        return handle_response(result)

    def post_state(self, local_state):
        result = requests.post(self.full_url('state/%s') % self.controller_id, local_state)
        return handle_response(result)

    def full_url(self, action):
        if self.controller_id is None:
            raise ClassNotReadyException("Controller id not set!")
        if self.url_base is None:
            raise ClassNotReadyException("URL base not set!")
        return self.url_base + '/' + action


def handle_response(response):
    if response.status_code != 200:
        raise ErrorCommunicatingWithServerException("Response not 200!")
    else:
        return response.json()
