from base64 import b64encode
import json
import socket
try:
    from httplib import HTTPConnection
except ImportError:
    from http.client import HTTPConnection

from .conf import settings
from . import EvoStreamException


class BaseProtocol(object):
    def execute(self, command, params=None):
        raise NotImplementedError()


class HTTPProtocol(BaseProtocol):
    @staticmethod
    def make_uri(command, **params):
        uri = '/%s' % command
        if len(params) > 0:
            str_params = ' '.join(['%s=%s' % (i, params[i]) for i in params])
            uri += '?params=%s' % b64encode(str_params)
        return uri

    def execute(self, command, **params):
        conn = HTTPConnection(settings.EVOSTREAM_URL)
        uri = self.make_uri(command, **params)
        try:
            conn.request('GET', uri)
        except socket.error as ex:
            raise EvoStreamException(ex)
        response = conn.getresponse()
        out = json.loads(response.read())
        if out['status'] == 'FAIL':
            raise EvoStreamException(out['description'])
        else:
            return out['data']

@@ -246,39 +246,42 @@
 bject):%0A    def 
-execute
+get_result
 (self, command, 
@@ -284,19 +284,16 @@
 nd, 
+**
 params
-=None
 ):%0A 
@@ -325,16 +325,226 @@
 edError(
+)%0A%0A    def parse_result(self, result):%0A        raise NotImplementedError()%0A%0A    def execute(self, command, **params):%0A        result = self.get_result(command, **params)%0A%0A        return self.parse_result(result
 )%0A%0A%0Aclas
@@ -840,39 +840,42 @@
 rn uri%0A%0A    def 
-execute
+get_result
 (self, command, 
@@ -1158,18 +1158,89 @@
         
-ou
+return response.read()%0A%0A    def parse_result(self, result):%0A        resul
 t = json
@@ -1249,28 +1249,19 @@
 oads(res
-ponse.read()
+ult
 )%0A      
@@ -1265,18 +1265,21 @@
      if 
-ou
+resul
 t%5B'statu
@@ -1330,18 +1330,21 @@
 ception(
-ou
+resul
 t%5B'descr
@@ -1390,10 +1390,13 @@
 urn 
-ou
+resul
 t%5B'd

refactor protocol class