import json
import requests

class DataBuffer:
    def __init__(self, url):
        self.url = url
    
    def get_response(self, response, is_json=True):
        if response.status_code != 200: 
           raise Exception(response.text)
        return json.loads(response.text) if is_json else response.text

    def get_binary_response(self, response):
        if response.status_code != 200: 
           raise Exception(response.text)
        return  response.raw.read()     

    def get_data(self, req):
        return self.get_response(requests.post(url=self.url+"/query", json=req))    

    def get_channels(self):
        data = {
           "regex":"DWSC090",
           "backends":[
              "sf-databuffer"
           ],
           "ordering":"asc",
           "reload":True
        }
        print self.url+"/channels"
        return self.get_response(requests.post(url=self.url+"/channels", json=data))    



req = {
           "channels":[
              "SINDI01-DWSC090:SCANNING",
              "SINDI01-DWSC090:ENC_1_BS"
           ],
           "range":{
              #"startPulseId":0,
              #"endPulseId":3
        
           "startDate":"2019-03-29T10:03:00.000",
           "startInclusive":True,
           "startExpansion":False,
           "endDate":"2019-03-29T10:07:00.000",
           "endInclusive":True,
           "endExpansion":False
        
              
           },
           "ordering":"asc",
           "configFields":[
              "globalDate",
              "type"
           ],
           "eventFields":[
              "pulseId",
              "globalDate",
              "value"
           ],
           "aggregation":{
              "aggregationType":"value",
              "aggregations":[
                 "min",
                 "mean",
                 "max"
              ],
              "nrOfBins":2
           },
           "response":{
              "format":"json",
              "compression":"none",
           },
           "mapping":{
              "incomplete":"provide-as-is"
           }
        }

db = DataBuffer ("https://data-api.psi.ch/sf")
c = db.get_channels()
ret = db.get_data(req)