#
# 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) 2016-2017 Anuta Networks, Inc. All Rights Reserved.
#

#
#DO NOT EDIT THIS FILE ITS AUTOGENERATED ONE
#ALL THE CUSTOMIZATIONS REGARDING DATAPROCESSING SHOULD BE WRITTEN INTO service_customization.py FILE
#
"""
Tree Structure of Handled XPATH:

services
        |
        day1services
                    |
                    day1service
                               |
                               tacacs-user-connectivity
                                                       |
                                                       tacacs-user-credentials
                                                                              
Schema Representation:

/services/day1services/day1service/tacacs-user-connectivity/tacacs-user-credentials
"""

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

from tclday0config.tclday0config_lib import getLocalObject
from tclday0config.tclday0config_lib import getDeviceObject
from tclday0config.tclday0config_lib import getCurrentObjectConfig
from tclday0config.tclday0config_lib import ServiceModelContext
from tclday0config.tclday0config_lib import getParentObject
from tclday0config.tclday0config_lib import log

#from servicemodel.controller import devices
from servicemodel.controller.devices.device import snmp
from expectj import ExpectJ
from expectj import SshSpawn
import service_customization


class TacacsUserCredentials(yang.AbstractYangServiceHandler):
    _instance = None

    def __init__(self):
        self.delete_pre_processor = service_customization.DeletePreProcessor()
        self.create_pre_processor = service_customization.CreatePreProcessor()
        self.opaque_args = {}

    def create(self, id, sdata):
        sdata.getSession().addYangSessionPreReserveProcessor(self.create_pre_processor)

        #Fetch Local Config Object
        config = getCurrentObjectConfig(id, sdata, 'tacacs_user_credentials')

        #Fetch Service Model Context Object
        smodelctx = None

        #Fetch Parent Object
        parentobj = None

        dev = []
        inputkeydict = {}
        devbindobjs={}
        inputdict = {}
        opaque_args = self.opaque_args

        # START OF FETCHING THE LEAF PARAMETERS
        inputdict['name'] = config.get_field_value('name')
        inputdict['username'] = config.get_field_value('username')
        inputdict['password'] = config.get_field_value('password')
        inputdict['result'] = config.get_field_value('result')
        # END OF FETCHING THE LEAF PARAMETERS
        password1 = util.decode_password(inputdict['password'])
	inputdict['password'] = password1

        _Gen_obj = getLocalObject(sdata, 'day1service')
        device_mgmt_ip_address = _Gen_obj.day1service.device_ip

        #Fetch Device Object
        dev = getDeviceObject(device_mgmt_ip_address, sdata)

        device_output = devicemgr.getDeviceById(device_mgmt_ip_address)
        cred_url = "/app/restconf/data/credentials/credential-sets/credential-set=%s" %(device_output.device.credential_set)
        cred_out = yang.Sdk.getData(cred_url,'',sdata.getTaskId())
        obj = util.parseXmlString(cred_out)
        log(obj.credential_set.transport_type)


        # START OF FETCHING THE PARENT KEY LEAF PARAMETERS
        inputkeydict['day1services_day1service_device_ip'] = sdata.getRcPath().split('/')[-3].split('=')[1]
        # END OF FETCHING THE PARENT KEY LEAF PARAMETERS

        #Use the custom methods to process the data
        service_customization.ServiceDataCustomization.process_service_create_data(smodelctx, sdata, dev, id=id, device=dev, parentobj=parentobj, inputdict=inputdict, inputkeydict=inputkeydict, config=config, hopaque=opaque_args)

        #Start of Device binding with python bindings
        #End of Device binding
        #Use the custom method to process/create payload
        service_customization.ServiceDataCustomization.process_service_device_bindings(smodelctx, sdata, dev, id=id, device=dev, inputdict=inputdict, inputkeydict=inputkeydict, parentobj=parentobj, config=config, devbindobjs=devbindobjs, hopaque=opaque_args)
        payload = '<input><device-id>%s</device-id><username>%s</username><password>%s</password><transport>%s</transport><terminal-mode>LOGIN</terminal-mode></input>' % (device_mgmt_ip_address,inputdict['username'],inputdict['password'],obj.credential_set.transport_type)
        copy_output = yang.Sdk.invokeRpc('controller:check-connectivity', payload)
        copy_output_tag = '<output>%s</output>' % (copy_output)
        xml_copyout = util.parseXmlString(copy_output_tag)
        if xml_copyout.output.result == "SUCCESS":
            payload = "<%s>%s</%s>" % ('result', 'pass', 'result')
            yang.Sdk.createData(sdata.getRcPath(), payload, sdata.getSession())
            yang.Sdk.append_taskdetail(sdata.getTaskId(), "Authentication passed on device %s with username %s" % (device_mgmt_ip_address,inputdict['username']))
        else:
            payload = "<%s>%s</%s>" % ('result', 'fail', 'result')
            yang.Sdk.createData(sdata.getRcPath(), payload, sdata.getSession())
            yang.Sdk.append_taskdetail(sdata.getTaskId(), xml_copyout.output.message)

    def update(self, id, sdata):
        #Fetch Local Config Object
        config = getCurrentObjectConfig(id, sdata, 'tacacs_user_credentials')
        opaque_args = self.opaque_args

        #Fetch Service Model Context Object
        smodelctx = None

        #Fetch Parent Object
        parentobj = None

        dev = []
        inputkeydict = {}
        devbindobjs={}
        inputdict = {}
        opaque_args = self.opaque_args

        # START OF FETCHING THE LEAF PARAMETERS
        prevconfig = util.parseXmlString(sdata.getPreviousPayload())
        inputdict['name'] = prevconfig.tacacs_user_credentials.name
        inputdict['username'] = prevconfig.tacacs_user_credentials.username
        inputdict['password'] = prevconfig.tacacs_user_credentials.password
        inputdict['result'] = prevconfig.tacacs_user_credentials.result
        # END OF FETCHING THE LEAF PARAMETERS

        password1 = util.decode_password(inputdict['password'])
	inputdict['password'] = password1
        _Gen_obj = getLocalObject(sdata, 'day1service')
        device_mgmt_ip_address = _Gen_obj.day1service.device_ip

        #Fetch Device Object
        dev = getDeviceObject(device_mgmt_ip_address, sdata)
        device_output = devicemgr.getDeviceById(device_mgmt_ip_address)
        cred_url = "/app/restconf/data/credentials/credential-sets/credential-set=%s" %(device_output.device.credential_set)
        cred_out = yang.Sdk.getData(cred_url,'',sdata.getTaskId())
        obj = util.parseXmlString(cred_out)
        log(obj.credential_set.transport_type)
        #Use the custom method to process the data
        service_customization.ServiceDataCustomization.process_service_update_data(smodelctx, sdata, id=id, dev=dev, parentobj=parentobj, config=config, hopaque=opaque_args, inputdict=inputdict)
        payload = '<input><device-id>%s</device-id><username>%s</username><password>%s</password><transport>%s</transport><terminal-mode>LOGIN</terminal-mode></input>' % (device_mgmt_ip_address,inputdict['username'],inputdict['password'],obj.credential_set.transport_type)
        copy_output = yang.Sdk.invokeRpc('controller:check-connectivity', payload)
        copy_output_tag = '<output>%s</output>' % (copy_output)
        xml_copyout = util.parseXmlString(copy_output_tag)
        if xml_copyout.output.result == "SUCCESS":
            payload = "<%s>%s</%s>" % ('result', 'pass', 'result')
            yang.Sdk.createData(sdata.getRcPath(), payload, sdata.getSession())
            yang.Sdk.append_taskdetail(sdata.getTaskId(), "Authentication passed on device %s with username %s" % (device_mgmt_ip_address,inputdict['username']))
        else:
            payload = "<%s>%s</%s>" % ('result', 'fail', 'result')
            yang.Sdk.createData(sdata.getRcPath(), payload, sdata.getSession())
            yang.Sdk.append_taskdetail(sdata.getTaskId(), xml_copyout.output.message)

    def delete(self, id, sdata):
        sdata.getSession().addYangSessionPreReserveProcessor(self.delete_pre_processor)

        #Fetch Local Config Object
        config = getCurrentObjectConfig(id, sdata, 'tacacs_user_credentials')
        opaque_args = self.opaque_args

        #Fetch Service Model Context Object
        smodelctx = None

        #Fetch Parent Object
        parentobj = None

        dev = []
        inputkeydict = {}
        devbindobjs={}
        inputdict = {}
        opaque_args = self.opaque_args

        # START OF FETCHING THE LEAF PARAMETERS
        inputdict['name'] = config.get_field_value('name')
        inputdict['username'] = config.get_field_value('username')
        inputdict['password'] = config.get_field_value('password')
        inputdict['result'] = config.get_field_value('result')
        # END OF FETCHING THE LEAF PARAMETERS

        _Gen_obj = getLocalObject(sdata, 'day1service')
        device_mgmt_ip_address = _Gen_obj.day1service.device_ip

        #Fetch Device Object
        dev = getDeviceObject(device_mgmt_ip_address, sdata)

        #Use the custom method to process the data
        service_customization.ServiceDataCustomization.process_service_delete_data(smodelctx, sdata, id=id, dev=dev, parentobj=parentobj, config=config, hopaque=opaque_args, inputdict=inputdict)

    @staticmethod
    def getInstance():
        if(TacacsUserCredentials._instance == None):
            TacacsUserCredentials._instance = TacacsUserCredentials()
        return TacacsUserCredentials._instance

    def rollbackCreate(self, id, sdata):
        log('rollback: id = %s, sdata = %s' % (id, sdata))
        self.delete(id,sdata)

if __name__ == 'tacacs_user_credentials':
  from servicemodel.yang import YangServiceData
  sdata = YangServiceData()
  instance = TacacsUserCredentials().getInstance()
  instance.create(None, sdata)
  instance.delete(None, sdata)
  instance.update(None, sdata)
