#
# This computer program is the confidential information and proprietary trade
# secret of Anuta Networks, Inc. Possessions and use of this program must
# conform strictly to the license agreement between the user and
# Anuta Networks, Inc., and receipt or possession does not convey any rights
# to divulge, reproduce, or allow others to use this program without specific
# written authorization of Anuta Networks, Inc.
#
# Copyright (c) 2015-2016 Anuta Networks, Inc. All Rights Reserved.
#

#
#DO NOT EDIT THIS FILE ITS AUTOGENERATED ONE
#

from servicemodel import util
from servicemodel import yang
from servicemodel import devicemgr
import copy

day1services_debug = False

def log(s):
  if day1services_debug:
    print s

def getCurrentObjectConfig(id, sdata, currentobj):
    log('id = %s, serviceData = %s' % (id, sdata))
    log('payload: %s' % (sdata.getPayload()))

    # using util library to parse xml
    # sdata.getPayload() will return a XML string posted by user
    config = util.parseXmlString(sdata.getPayload())
    if currentobj is not None and hasattr(config, currentobj):
      config = getattr(config, currentobj)
    else:
      log('%s attribute not present in current configuration'%currentobj)
      return None
    log(config.toXml())
    return config

def getInputDict(config):
    inputattribs = config.__dict__
    inputdict=copy.deepcopy(inputattribs)
    return inputdict

def getDeviceObject(mgmt_leaf, sdata = None):
    key = 'device.%s' % (mgmt_leaf)
    if sdata != None:
        dev = sdata.getSessionItem(key)
        if dev != None:
            log('getDeviceObject:cache-hit key=%s' % (key))
            return dev
        else:
            log('getDeviceObject:cache-miss key=%s' % (key))

    dev = []
    for device in util.convert_to_list(mgmt_leaf):
        dev_object = devicemgr.getDeviceById(device)
        if (dev_object == None):
            log('No device by ip: %s' % (mgmt_leaf))
            raise Exception('No device by ip: %s' % (mgmt_leaf))
        dev.append(dev_object)
    if sdata != None:
        sdata.setSessionItem(key, dev, True)
    return dev

def getParentObject(sdata):
    """
    rcpath =  util.get_parent_rcpath(sdata.getRcPath())
    #log('setting rcpath= %s' % (rcpath))

    xml_output = yang.Sdk.getData(rcpath, '', sdata.getTaskId())
    obj = util.parseXmlString(xml_output)

    return obj
    """

    rcpath =  util.get_parent_rcpath(sdata.getRcPath())
    #log('setting rcpath= %s' % (rcpath))

    key = 'parent.%s' % (rcpath)
    obj = sdata.getSessionItem(key)
    if obj != None:
        log('getParentObject:cache-hit key=%s' % (key))
        return obj
    #log('getParentObject:cache-miss key=%s' % (key))
    xml_output = yang.Sdk.getData(rcpath, '', sdata.getTaskId())
    obj = util.parseXmlString(xml_output)
    if obj != None:
      sdata.setSessionItem(key, obj, True)

    return obj

def find_exact_match_first_occurance (rcpath, elem, relativedist):
    idx = rcpath.find(elem)
    if idx < 0:
        log('cant find pattern %s in rcpath = %s - find_exact_match_first_occurance' % (elem, rcpath))
        return relativedist
    idx = rcpath.find('/', idx)
    if idx < 0:
        log('cant find / in rcpath = %s, idx = %d - find_exact_match_first_occurance' % (rcpath, idx))
        return relativedist

    trcpath = rcpath[:idx]
    relativedist = relativedist + idx
    if trcpath.split('/')[-1] != elem:
        trcpath = rcpath[idx:]
        return find_exact_match_first_occurance(trcpath, elem, relativedist)
    return relativedist


def getLocalObject(sdata, elem):
    rcpath = sdata.getRcPath()
    log('rcpath = %s' % (rcpath))
    pattern = '/controller:services'
    idx = rcpath.find(pattern)
    if idx < 0:
        log('cant find pattern in rcpath = %s' % (rcpath))
        return rcpath

    idx = find_exact_match_first_occurance(rcpath, elem, 0)
    log('rcpath = %s, new = %s' % (rcpath, rcpath[:idx]))
    rcpath = rcpath[:idx]

    key = 'local.%s' % (rcpath)
    obj = sdata.getSessionItem(key)
    if obj == None:
        log('getLocalObject:cache-miss key=%s' % (key))
        xml_output = yang.Sdk.getData(rcpath, '', sdata.getTaskId())
        log('%s object: %s' % (elem, xml_output))
        obj = util.parseXmlString(xml_output)
        sdata.setSessionItem(key, obj, True)
    else:
        log('getLocalObject:cache-hit key=%s' % (key))

    return obj

class ServiceModelContext(yang.ServiceModelContext):
    def __init__(self, id, sdata):
        yang.ServiceModelContext.__init__(self, id, sdata)
        #self.load_service_object()

    def load_service_object(self):
        pattern = '/controller:services/tclday0config:day1services'
        # self.service_rcpath = pattern
        # #log('setting rcpath = %s' % (self.service_rcpath))
        # yang.ServiceModelContext.load_service_object(self, self.service_rcpath)
        # self.service_obj = self.service_xmlobj
        # #log('[ServiceModelContext]service_obj: %s, tostr: %s' % (self.service_obj, self.service_obj.toXml()))
        key = 'service_object.%s' % (self.service_rcpath)
        obj = self.sdata.getSessionItem(key)
        if obj != None:
            log('load_service_object:cache-hit key=%s' % (key))
            self.service_obj = obj
            log('Getting service object from cache. rcPath = %s' % (self.service_rcpath))
            return obj
        log('load_service_object:cache-miss key=%s' % (key))
        self.service_rcpath = pattern
        log('setting rcpath = %s' % (self.service_rcpath))
        yang.ServiceModelContext.load_service_object(self, self.service_rcpath)
        self.service_obj = self.service_xmlobj
        #log('[ServiceModelContext]service_obj: %s' % (self.service_obj))
        obj = self.service_obj
        self.sdata.setSessionItem(key, obj, True)
        return obj