# -*- coding: utf-8 -*-
# Copyright 2017 Objectif Libre
#
#    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.
#
import datetime
import decimal

from gnocchiclient import client as gclient
from gnocchiclient import exceptions as gexceptions
from keystoneauth1 import loading as ks_loading
from oslo_config import cfg
from oslo_log import log as logging
from oslo_utils import uuidutils

from cloudkitty.collector import validate_conf
from cloudkitty.storage.v1.hybrid.backends import BaseHybridBackend
import cloudkitty.utils as ck_utils
from cloudkitty.utils import json


LOG = logging.getLogger(__name__)

CONF = cfg.CONF

CONF.import_opt('period', 'cloudkitty.collector', 'collect')

GNOCCHI_STORAGE_OPTS = 'storage_gnocchi'
gnocchi_storage_opts = [
    cfg.StrOpt('interface',
               default='internalURL',
               help='endpoint url type'),
    cfg.StrOpt('archive_policy_name',
               default='rating',
               help='Gnocchi storage archive policy name.'),
    # The archive policy definition MUST include the collect period granularity
    cfg.StrOpt('archive_policy_definition',
               default='[{"granularity": '
                       + str(CONF.collect.period) +
                       ', "timespan": "90 days"}, '
                       '{"granularity": 86400, "timespan": "360 days"}, '
                       '{"granularity": 2592000, "timespan": "1800 days"}]',
               help='Gnocchi storage archive policy definition.'), ]
CONF.register_opts(gnocchi_storage_opts, GNOCCHI_STORAGE_OPTS)

ks_loading.register_session_conf_options(
    CONF,
    GNOCCHI_STORAGE_OPTS)
ks_loading.register_auth_conf_options(
    CONF,
    GNOCCHI_STORAGE_OPTS)

RESOURCE_TYPE_NAME_ROOT = 'rating_service_'
METADATA_NAME_ROOT = 'ckmeta_'


class UnknownResourceType(Exception):
    """Exception raised when an unknown resource type is encountered"""

    def __init__(self, resource_type):