from collections import defaultdict

import feather
import pandas

from besser_tanken.config import stations_dir


def group_prices(prices):
    grouped_prices = defaultdict(list)
    for p in prices:
        grouped_prices[p['station_uuid']].append(p)
    return grouped_prices


def fix_date_time_strings(price_dict_list):
    for p in price_dict_list:
        try:
            date_time_string, tz_string = p['date'].rsplit('+', maxsplit=1)
            if ':' in tz_string:
                tz_string.replace(':', '')
            else:
                tz_string_len = len(tz_string)
                if tz_string_len < 4:
                    tz_string += '0' * (4 - tz_string_len)
            p['date'] = date_time_string + "+" + tz_string
        except IndexError:
            pass

    return price_dict_list


def convert_csv_to_feather(csv_file: str, feather_file: str = None):
    path = 'my_data.feather'
    df = pandas.read_csv(csv_file)
    if feather_file is None:
        feather_file = csv_file.rsplit('.', maxsplit=1)[0] + '.feather'
    feather.write_dataframe(df, feather_file)
    # df = feather.read_dataframe(path)


if __name__ == '__main__':
    convert_csv_to_feather(f"{stations_dir}/2021/01/2021-01-01-stations.csv")
