# Copyright (C) [2015-2017] [Thomson Reuters LLC]
# Copyright (C) [2015-2017] [Panos Kittenis]

# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at

#     http://www.apache.org/licenses/LICENSE-2.0

# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""InfluxGraph utility functions"""

from __future__ import absolute_import, print_function

import datetime
import sys
import re
import hashlib

import memcache
from .constants import INFLUXDB_AGGREGATIONS

try:
    from .ext.nodetrie import Node
except ImportError:
    from .classes.tree import NodeTreeIndex as Node

try:
    from .ext.templates import get_series_with_tags, heapsort, \
        _make_path_from_template
except ImportError:
    from .templates import get_series_with_tags, heapsort, \
        _make_path_from_template


def calculate_interval(start_time, end_time, deltas=None):
    """Calculates wanted data series interval according to start and end times

    Returns interval in seconds
    :param start_time: Start time in seconds from epoch
    :param end_time: End time in seconds from epoch
    :type start_time: int
    :type end_time: int
    :param deltas: Delta configuration to use. Defaults hardcoded if no
      configuration is provided
    :type deltas: dict(max time range of query in seconds: interval to use
      in seconds)

    :rtype: int - *Interval in seconds*
    """
    time_delta = end_time - start_time
    deltas = deltas if deltas else {
        # 15 min -> 10s
        900: 10,
        # 30 min -> 30s
        1800: 30,
        # # 1 hour -> 1s
        # 3600 : 1,
        # # 1 day -> 30s
        # 86400 : 30,
        # 3 days -> 1min
        259200: 60,
        # 7 days -> 5min
        604800: 300,
        # 14 days -> 10min
        1209600: 600,
        # 28 days -> 15min
        2419200: 900,
        # 2 months -> 30min
        4838400: 1800,
        # 4 months -> 1hour
        9676800: 3600,
        # 12 months -> 3hours
        31536000: 7200,
        # 4 years -> 12hours
        126144000: 43200,
        }
    for delta in sorted(deltas.keys()):
        if time_delta <= delta:
            return deltas[delta]
    # 1 day default, or if time range > max configured (4 years default max)
    return 86400


def get_retention_policy(interval, retention_policies):
    """Get appropriate retention policy for interval provided

    :param interval: Interval of query in seconds
    :type interval: int
    :param retention_policies: Retention policy configuration
    :type retention_policies: dict(max time range of interval