'''
Copyright (c) 2014, Emmanuel Levijarvi
All rights reserved.
License BSD
'''
import logging
import datetime
from iotrelay import Reading
from pywws import DataStore

__version__ = "1.0.0"

logger = logging.getLogger(__name__)

# hours to look back for readings
DEFAULT_LOOKBACK = 2
READING_TYPE = 'weather'


class Poll(object):
    def __init__(self, config):
        self.keys = [k.strip() for k in config['series keys'].split(',')]
        self.data_store = config['data store']
        poll_frequency = int(config['poll frequency'])
        self.delta = datetime.timedelta(seconds=poll_frequency)
        lookback = int(config.get('lookback', DEFAULT_LOOKBACK))
        hours = datetime.timedelta(hours=lookback)
        self.last_ts = datetime.datetime.utcnow() - hours

    def get_readings(self):
        current_timestamp = datetime.datetime.utcnow()
        if current_timestamp < self.last_ts + self.delta:
            logger.debug('pywws {0!s} until next reading'.format(
                         self.last_ts + self.delta - current_timestamp))
            return ()
        readings = DataStore.data_store(self.data_store)
        for reading in readings[self.last_ts:]:
            for key in self.keys:
                yield Reading(READING_TYPE, reading[key], reading['idx'], key)
        self.last_ts = current_timestamp

@@ -482,127 +482,8 @@
 e'%5D%0A
-        poll_frequency = int(config%5B'poll frequency'%5D)%0A        self.delta = datetime.timedelta(seconds=poll_frequency)%0A
     
@@ -693,378 +693,181 @@
     
-current_timestamp = datetime.datetime.utcnow()%0A        if current_timestamp %3C self.last_ts + self.delta:%0A            logger.debug('pywws %7B0!s%7D until next reading'.format(%0A                         self.last_ts + self.delta - current_timestamp))%0A            return ()%0A        readings = DataStore.data_store(self.data_store)%0A        for reading in readings%5Bself.last_ts:%5D:
+for data in DataStore.data_store(self.data_store)%5Bself.last_ts:%5D:%0A            if data%5B'idx'%5D %3C= self.last_ts:%0A                continue%0A            self.last_ts = data%5B'idx'%5D
 %0A   
@@ -945,80 +945,33 @@
 PE, 
-reading%5Bkey%5D, reading%5B'idx'%5D, key)%0A        self.last_ts = current_timestamp
+data%5Bkey%5D, data%5B'idx'%5D, key)
 %0A

use last reading timestamp as the early endpoint when fetching new readings