#!/usr/bin/python
#
# Copyright (c) 2015 Dell Inc.
#
# 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
#
# THIS CODE IS PROVIDED ON AN #AS IS* BASIS, WITHOUT WARRANTIES OR
# CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT
#  LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS
# FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.
#
# See the Apache Version 2.0 License for specific language governing
# permissions and limitations under the License.
#

# Generic CPS data storage that responds to all CPS requests
# CPS service performs a longest-prefix match, so by registering at the root,
# if there is no other match for the CPS key, CPS will pass the request to
# this script

import cps
import time

# Create the standard data store
data_store = dict()

# CPS Get handler
def get_cb(methods, params):
    retval = False
    # print "Get...", params
    key = params['filter']['key']
    # For all keys that match the prefix
    for ds_key in data_store.keys():
        if ds_key.startswith(key):
            params['list'].append(data_store[ds_key])
            retval = True

    return retval

# CPS Transaction handler
def transaction_cb(methods, params):
    # print "Trans...", params
    op = params['operation']
    if (op == 'set') or (op == 'create'):
        # Create a new entry in our data store
        data_store[params['change']['key']] = params['change']
    elif (op == 'delete'):
        # Delete an entry from the data store
        key = params['change']['key']
        if not key in data_store:
            return False
        del data_store[key]
    else:
        # Unknown operation
        return False

    return True

# Register for CPS
reg = dict()
reg['get'] = get_cb
reg['transaction'] = transaction_cb
cps_handle = cps.obj_init()
cps.obj_register(cps_handle, '', reg)

# Wait for responses
while True:
    time.sleep(1)
