"""
this is pack of tools that should be used externally
"""
import logging
from datetime import datetime, date, timedelta
from dateutil import tz

from algo.data.reader import get_data_reader
from algo.data.common import Symbol
from algo.util import get_week_start_day


log = logging.getLogger(__name__)


def cache_from_influx(weeks_back: int = 1):
    """
    reads data about last 3 weeks and caches it into the DynamoCache
    """
    log.info('about to start caching for last %s weeks', weeks_back)
    # todo: remove  3 days deduction in following
    current_week_start = get_week_start_day(date.today() - timedelta(days=23))
    for weeks_back in range(weeks_back):
        current_day = current_week_start - timedelta(days=weeks_back*7)
        period_start_date_time = datetime.combine(
            current_day, datetime.min.time(), tz.tzutc()
        )
        log.info('reading data for week starting %s', period_start_date_time)
        data_reader = get_data_reader()
        for cur_symbol in Symbol:
            log.info('getting %s', cur_symbol)
            days_with_data = 0
            for day_of_week in range(7):
                current_day_datetime = period_start_date_time + timedelta(days=day_of_week)
                log.info('verifying full data set day %s', current_day_datetime)
                data_stream = data_reader.get_data_stream(current_day_datetime, current_day_datetime + timedelta(days=1), cur_symbol)
                all_data = list(data_stream)
                log.info('-> data count: %s', len(all_data))
                if len(all_data) > 0:
                    days_with_data += 1
            #
            if days_with_data >= 5:
                log.info('enough data caching %s, %s', cur_symbol, current_day)
                week_data = data_reader.week_data(period_start_date_time.isoformat(), cur_symbol)
                log.info('total - data length %s', len(list(week_data)))
