#
# Copyright 2012 New Dream Network, LLC (DreamHost)
# Copyright 2013 IBM Corp.
# Copyright 2013 eNovance <licensing@enovance.com>
# Copyright Ericsson AB 2013. All rights reserved
# Copyright 2014 Hewlett-Packard Company
# Copyright 2015 Huawei Technologies Co., Ltd.
#
# 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 uuid
from webob import exc
from report.api.openstack import extensions
from report.api.openstack import wsgi
from report import exception
from report import storage
from webob import Response
from report.client import ceilometer_client
from oslo_log import log
import json
import time
ALIAS = "samples"

LOG = log.getLogger(__name__)

class SamplesController(wsgi.Controller):
    """Controller managing the samples."""

    def __init__(self, **kwargs):
        #self.extension_info = kwargs.pop('extension_info')
  
        #========================================#
        #url = 'hbase+hbase://127.0.0.1:9090'
        #namespace = 'report.storage'
        #self.dbconn = storage.get_connection(url, namespace)
        #========================================#

        #========================================#
        self.client = ceilometer_client.Client()
        #========================================#
        super(SamplesController, self).__init__(**kwargs)

    #@extensions.expected_errors((400, 403))
    def index(self, req):
        """Returns a list of server names and ids for a given user."""
        try:
            servers = self._get_samples(req, is_detail=False)
        except exception.Invalid as err:
            raise exc.HTTPBadRequest(explanation=err.format_message())
        return servers

    def _get_samples(self, req, is_detail):

        result = []
        search_opts = {}
        search_opts.update(req.GET)

        """
        kwargs = dict(user=None,
                      project=None,
                      meter='cpu',
                      #resource='0d16b51e-5c85-400f-a975-bdff3eb75485',
                      resource=None,
                      source=None,
                      message=None)
        limit = 1000
        if 'limit' in search_opts.keys():
            limit = int(search_opts['limit'])

        samples = self.dbconn.get_samples(kwargs, limit=limit)
        for sample in samples:
            jsonDumpData = json.dumps(sample)
            jsondata = json.loads(jsonDumpData)
            resource = jsondata['f:resource_id']
            name = jsondata['f:counter_name']
            times = json.loads(jsondata['f:timestamp'])['$date']
            
            d = dict(
                    timestamp = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(int(times)/1000)),
                    value = jsondata['f:counter_volume'],
                    unit = jsondata['f:counter_unit'] 
                )
      
            key = resource + "_" + name
            if key in result.keys():
                result[key].append(d)
            else:
                result[key] = [d]
        """

        limit = 1000
        meterlist = ['cpu', 'cpu_util', 'memory.resident']

        if "limit" in search_opts.keys():
            limit = int(search_opts['limit'])
            LOG.debug("request query limit:" + str(limit))
            req.GET.pop('limit')

        if "meter" in search_opts.keys():
            query_meter = str(search_opts['meter'])
            meterlist = [query_meter]
            LOG.debug("request query meter:" + query_meter)
            req.GET.pop('meter')

        meterinfos = {}

        for meter in meterlist:
            samples = self.client.get_samples(limit=limit, meter_name=meter)
            for sample in samples:
                resource_id = sample.resource_id
                meter_name = sample.counter_name

                key = resource_id + "_" + meter_name
                if key in meterinfos.keys():
                    meterobj = meterinfos[key]
                else:
                    meterobj = MeterInfo(resource_id, meter_name)
                    meterinfos[key] = meterobj
                #samplesinfo['resource_metadata'] = sample.resource_metadata
 
                d = dict(
                        timestamp = str(sample.timestamp),
                        value = str(sample.counter_volume),
                        unit = str(sample.counter_unit),
                    )
            
                meterobj.values.append(d)            

        for obj in meterinfos.values():
           #s = json.dumps(obj, default=convert_to_builtin_type)
           #print s
           result.append(obj)

        #print result
        datas = json.dumps(result, default=convert_to_builtin_type)
        res = Response(datas)
        res.headers.add("Access-Control-Allow-Origin","*")
        
        return res

    @extensions.expected_errors(404)
    def show(self, req, id='v2.1'):
        """
        builder = views_versions.get_view_builder(req)
        if id not in versions.VERSIONS:
            raise webob.exc.HTTPNotFound()

        return builder.build_version(versions.VERSIONS[id])
        """
        return "Samples show, req:" + str(req)

class Samples(extensions.V3APIExtensionBase):
    """Servers."""

    name = "Samples"
    alias = ALIAS
    version = 1

    def get_resources(self):
        member_actions = {'action': 'POST'}
        collection_actions = {'detail': 'GET'}

        """
        resources = [
            extensions.ResourceExtension(
                ALIAS,
                SamplesController(extension_info=self.extension_info),
                member_name='sample', collection_actions=collection_actions,
                member_actions=member_actions)]
        """
        resources = [
            extensions.ResourceExtension(ALIAS, SamplesController())
            ]
        return resources

    def get_controller_extensions(self):
        return []

class MeterInfo(object):
    def __init__(self, resource_id, meter_name):
        self.resource_id = resource_id
        self.meter_name = meter_name
        self.values = []

def convert_to_builtin_type(obj):
    d = {}
    d.update(obj.__dict__)
    return d
