# Path: historisation/historisation/storages/local.py
# class LocalStorage(Storage):
#     def __init__(self, root_dir='test', schema='schema'):
#         super(Storage, self).__init__()
#         self.streamable = True
#         self.root_dir = root_dir
#         self.schema = schema
# 
#         try:
#             os.makedirs(root_dir)
#         except OSError as exc:
#             if exc.errno == errno.EEXIST and os.path.isdir(root_dir):
#                 pass
#             else:
#                 logger.exception(exc)
#                 raise exc
# 
#     def get(self, path):
#         with open(os.path.join(self.root_dir, path), 'r') as f:
#             return f.read()
# 
#     def exists(self, path):
#         return os.path.isfile(os.path.join(self.root_dir, path))
# 
#     def save(self, path, lines):
#         with open(os.path.join(self.root_dir, path), 'a') as f:
#             for line in lines:
#                 f.write(line)
# 
#     def mkdir(self, path):
#         try:
#             os.mkdir(os.path.join(self.root_dir, path))
#         except OSError:
#             pass
# 
#     def get_dirs(self):
#         return os.listdir(self.root_dir)
# 
#     def get_files(self, path):
#         def _file_getctime(filename):
#             return os.path.getctime(os.path.join(self.root_dir, path, filename))
# 
#         return sorted(os.listdir(os.path.join(self.root_dir, path)), key=_file_getctime)
# 
#     def move(self, source, dest):
#         shutil.move(os.path.join(self.root_dir, source), os.path.join(self.root_dir, dest))
# 
#     def join(self, *paths):
#         return os.path.join(*paths)


import datetime
import re
import sys
import requests
import logging
import tempfile
import csv
import errno
from collections import OrderedDict
from .storages import LocalStorage
                line += '%s%s' % (self.delimiter, self.timestamp_fieldname)
            else:
                line += '%s%s' % (self.delimiter, fetch_time.isoformat())
            tmp_f.write(line + '\n')

        return tmp_f, fetch_time

    def fetch_aggregations(self, select=None, where=None, group_by=None, map_on=None):
        fetch_time = self.get_time()
        tmp_f = self.get_temp_file()

        aggregations = []

        if map_on:
            r = requests.get(self.base_url + 'aggregates', stream=True, timeout=30, params={
                'select': map_on,
                'group_by': map_on,
                'apikey': self.apikey
            })

            r.raise_for_status()

            jobs = [aggregation[map_on] for aggregation in r.json()['aggregations']]
            for i, job in enumerate(jobs):
                map_where = map_on + '=' + str(job)
                if where:
                    map_where = map_where + ' AND ' + where

                aggregations.extend(self._fetch_aggregations(select=select, where=map_where, group_by=group_by))
        else:

# Path: historisation/historisation/storages/local.py
# class LocalStorage(Storage):
#     def __init__(self, root_dir='test', schema='schema'):
#         super(Storage, self).__init__()
#         self.streamable = True
#         self.root_dir = root_dir
#         self.schema = schema
# 
#         try:
#             os.makedirs(root_dir)
#         except OSError as exc:
#             if exc.errno == errno.EEXIST and os.path.isdir(root_dir):
#                 pass
#             else:
#                 logger.exception(exc)
#                 raise exc
# 
#     def get(self, path):
#         with open(os.path.join(self.root_dir, path), 'r') as f:
#             return f.read()
# 
#     def exists(self, path):
#         return os.path.isfile(os.path.join(self.root_dir, path))
# 
#     def save(self, path, lines):
#         with open(os.path.join(self.root_dir, path), 'a') as f:
#             for line in lines:
#                 f.write(line)
# 
#     def mkdir(self, path):
#         try:
#             os.mkdir(os.path.join(self.root_dir, path))
#         except OSError:
#             pass
# 
#     def get_dirs(self):
#         return os.listdir(self.root_dir)
# 
#     def get_files(self, path):
#         def _file_getctime(filename):
#             return os.path.getctime(os.path.join(self.root_dir, path, filename))
# 
#         return sorted(os.listdir(os.path.join(self.root_dir, path)), key=_file_getctime)
# 
#     def move(self, source, dest):
#         shutil.move(os.path.join(self.root_dir, source), os.path.join(self.root_dir, dest))
# 
#     def join(self, *paths):
#         return os.path.join(*paths)


# Path: historisation/historisation/historifier.py
import datetime
import re
import sys
import requests
import logging
import tempfile
import csv
import errno
from collections import OrderedDict
from .storages import LocalStorage

                line += '%s%s' % (self.delimiter, self.timestamp_fieldname)
            else:
                line += '%s%s' % (self.delimiter, fetch_time.isoformat())
            tmp_f.write(line + '\n')

        return tmp_f, fetch_time

    def fetch_aggregations(self, select=None, where=None, group_by=None, map_on=None):
        fetch_time = self.get_time()
        tmp_f = self.get_temp_file()

        aggregations = []

        if map_on:
            r = requests.get(self.base_url + 'aggregates', stream=True, timeout=30, params={
                'select': map_on,
                'group_by': map_on,
                'apikey': self.apikey
            })

            r.raise_for_status()

            jobs = [aggregation[map_on] for aggregation in r.json()['aggregations']]
            for i, job in enumerate(jobs):
                map_where = map_on + '=' + str(job)
                if where:
                    map_where = map_where + ' AND ' + where

                aggregations.extend(self._fetch_aggregations(select=select, where=map_where, group_by=group_by))
        else:

            aggregations = self._fetch_aggregations(select=select, where=where, group_by=group_by)