# Path: telostats/stations/models.py
# class Station(models.Model):
#     id = models.IntegerField(unique=True, primary_key=True)
#     name = models.CharField(u'name', max_length=100)
#     address = models.CharField(u'address', max_length=100, null=True, blank=True)
#     longitude = models.FloatField(u'longitude')
#     latitude = models.FloatField(u'latitude')
#     polygon = JSONField(u'polygon')
#     poles = models.IntegerField(u'poles')
#     available = models.IntegerField(u'available')
#     visible = models.BooleanField(u'visible', default=False)
# 
#     objects = models.Manager()
#     visible_objects = VisibleStationManager()
# 
#     def __unicode__(self):
#         return u'({}) {}'.format(self.id, self.name)
# 
#     def available_poles(self):
#         return self.available
# 
#     def available_bikes(self):
#         return self.poles - self.available
# 
# Path: telostats/utils/tempodb.py
# class TempoDbClient():
#     def __init__(self, key=TEMPODB_KEY, secret=TEMPODB_SECRET):
#         self.key = key
#         self.secret = secret
#         session_auth = requests.auth.HTTPBasicAuth(TEMPODB_KEY, TEMPODB_SECRET)
#         self.session = requests.session(auth=session_auth)
# 
#     def get_data(self, station_id=None, start=None, end=None, interval='1hour',
#             function='mean', tz='Asia/Jerusalem'):
#         params = {
#             'interval': interval,
#             'function': function,
#             'tz': tz
#         }
#         if start:
#             params['start'] = start
#         if end:
#             params['end'] = end
#         if station_id:
#             params['attr[station]'] = station_id
#         return self.session.get(API_URL + '/data/', params=params)
# 
#     def get_series(self, station_id=None, interval='1hour', start=timedelta(hours=24), **kwargs):
#         start = (datetime.utcnow() - start).isoformat()
#         data = self.get_data(station_id=station_id, start=start, interval=interval)
#         content = data.content
#         res = defaultdict(dict)
# 
#         d = json.loads(content)
#         for series in d:
#             station_id = series['series']['attributes']['station']
#             data_type = series['series']['tags'][0]
#             data_val = series['data']
#             res[station_id][data_type] = data_val
# 
#         return dict(res)
# 
#     def get_latest_counts(self, station_id=None):
#         '''This method is pending a proper get_latest API from tempo db'''
#         start = datetime.utcnow() - timedelta(minutes=15)
#         content = self.get_data(station_id=station_id, start=start).content
#         res = defaultdict(dict)
# 
#         d = json.loads(content)
#         for series in d:
#             station_id = series['series']['attributes']['station']
#             data_type = series['series']['tags'][0]
#             data_val = series['data'][-1]['v']
#             res[station_id][data_type] = data_val
# 
#         return dict(res)


import json
from datetime import datetime, timedelta
from dateutil.parser import parse as parse_date
from tastypie.cache import NoCache
from tastypie.resources import ModelResource, Resource, fields
from tastypie.serializers import Serializer
from .models import Station
from ..utils.tempodb import TempoDbClient
        poles = [x['v'] for x in series['poles']]
        series = [{
            'timestamp': t,
            'poles': p,
            'available': a,
            'bikes': p - a
        } for t, p, a in zip(timestamps, poles, available)]
        initial_series = {'series': series}
        station_series = StationSeries(initial=initial_series)
        station_series.id = station_id
        return station_series


class AverageResource(Resource):
    id = fields.CharField(attribute='id')
    series = fields.ListField(attribute='series')

    class Meta:
        object_class = StationSeries
        resource_name = 'average'
        cache = APICache(timeout=60 * 60 * 24 * 7)
        serializer = Serializer(formats=['json'])
        limit = 1
        list_allowed_methods = []
        detail_allowed_methods = ['get']
        filtering = {
            'id': ('exact', ),
        }

    def _client(self):

# Path: telostats/stations/models.py
# class Station(models.Model):
#     id = models.IntegerField(unique=True, primary_key=True)
#     name = models.CharField(u'name', max_length=100)
#     address = models.CharField(u'address', max_length=100, null=True, blank=True)
#     longitude = models.FloatField(u'longitude')
#     latitude = models.FloatField(u'latitude')
#     polygon = JSONField(u'polygon')
#     poles = models.IntegerField(u'poles')
#     available = models.IntegerField(u'available')
#     visible = models.BooleanField(u'visible', default=False)
# 
#     objects = models.Manager()
#     visible_objects = VisibleStationManager()
# 
#     def __unicode__(self):
#         return u'({}) {}'.format(self.id, self.name)
# 
#     def available_poles(self):
#         return self.available
# 
#     def available_bikes(self):
#         return self.poles - self.available
# 
# Path: telostats/utils/tempodb.py
# class TempoDbClient():
#     def __init__(self, key=TEMPODB_KEY, secret=TEMPODB_SECRET):
#         self.key = key
#         self.secret = secret
#         session_auth = requests.auth.HTTPBasicAuth(TEMPODB_KEY, TEMPODB_SECRET)
#         self.session = requests.session(auth=session_auth)
# 
#     def get_data(self, station_id=None, start=None, end=None, interval='1hour',
#             function='mean', tz='Asia/Jerusalem'):
#         params = {
#             'interval': interval,
#             'function': function,
#             'tz': tz
#         }
#         if start:
#             params['start'] = start
#         if end:
#             params['end'] = end
#         if station_id:
#             params['attr[station]'] = station_id
#         return self.session.get(API_URL + '/data/', params=params)
# 
#     def get_series(self, station_id=None, interval='1hour', start=timedelta(hours=24), **kwargs):
#         start = (datetime.utcnow() - start).isoformat()
#         data = self.get_data(station_id=station_id, start=start, interval=interval)
#         content = data.content
#         res = defaultdict(dict)
# 
#         d = json.loads(content)
#         for series in d:
#             station_id = series['series']['attributes']['station']
#             data_type = series['series']['tags'][0]
#             data_val = series['data']
#             res[station_id][data_type] = data_val
# 
#         return dict(res)
# 
#     def get_latest_counts(self, station_id=None):
#         '''This method is pending a proper get_latest API from tempo db'''
#         start = datetime.utcnow() - timedelta(minutes=15)
#         content = self.get_data(station_id=station_id, start=start).content
#         res = defaultdict(dict)
# 
#         d = json.loads(content)
#         for series in d:
#             station_id = series['series']['attributes']['station']
#             data_type = series['series']['tags'][0]
#             data_val = series['data'][-1]['v']
#             res[station_id][data_type] = data_val
# 
#         return dict(res)


# Path: telostats/stations/api.py
import json
from datetime import datetime, timedelta
from dateutil.parser import parse as parse_date
from tastypie.cache import NoCache
from tastypie.resources import ModelResource, Resource, fields
from tastypie.serializers import Serializer
from .models import Station
from ..utils.tempodb import TempoDbClient

        poles = [x['v'] for x in series['poles']]
        series = [{
            'timestamp': t,
            'poles': p,
            'available': a,
            'bikes': p - a
        } for t, p, a in zip(timestamps, poles, available)]
        initial_series = {'series': series}
        station_series = StationSeries(initial=initial_series)
        station_series.id = station_id
        return station_series


class AverageResource(Resource):
    id = fields.CharField(attribute='id')
    series = fields.ListField(attribute='series')

    class Meta:
        object_class = StationSeries
        resource_name = 'average'
        cache = APICache(timeout=60 * 60 * 24 * 7)
        serializer = Serializer(formats=['json'])
        limit = 1
        list_allowed_methods = []
        detail_allowed_methods = ['get']
        filtering = {
            'id': ('exact', ),
        }

    def _client(self):

        return TempoDbClient()