import simpleplugin
from simpleplugin.agent import Agent
import os, sys, time
from Queue import Queue
import whatap.value as whatapValue
import whatap.util.thread_util as thread_util
import whatap.util.logging_util as logging_util
from whatap.util.date_util import DateUtil as date_util
import whatap.agent.secure.security_master as secure
import whatap.agent.data.data_pack as data
from whatap.pack.tagcount_pack import TagCountPack
from whatap.pack.logsink_pack import LogSinkPack

def start():
	thread_util.async(_start)

agentFacade = None

def getAgent():
	global agentFacade
	if not agentFacade:
		raise Exception("agent not enabled")
	
	return agentFacade

def getInput(inputName):
	agentFacade = getAgent()
	
	return agentFacade.getInputToml(inputName)
	
def setInput(inputfile, inputToml ):
	# if !config.GetConfig().ExtensionUnlock {
	# 	err = fmt.Errorf("Modification failed. Extension read only mode")
	# 	return

	agentFacade = getAgent()
	
	agentFacade.setInputToml(inputfile, inputToml)
	
	return

def getAllInput():
	# if !config.GetConfig().ExtensionUnlock {
	# 	err = fmt.Errorf("Modification failed. Extension read only mode")
	# 	return
	
	agentFacade = getAgent()
	
	return agentFacade.getAllInput()

def deleteInput(inputfile ):
	# if !config.GetConfig().ExtensionUnlock {
	# 	err = fmt.Errorf("Modification failed. Extension read only mode")
	# 	return
	
	agentFacade = getAgent()
	
	agentFacade.deleteInput(inputfile)
	
	return


def _start():
	global agentFacade
	prefix = os.path.abspath(os.path.split(sys.argv[0])[0])
	pluginPrefix = os.path.join(prefix, "extension")
	if not os.path.exists(pluginPrefix):
		logging_util.debug("simpleplugin extension directory not found: {}".format(pluginPrefix))
		return
	
	try:
		agentFacade = Agent.newAgent(pluginPrefix)
	except Exception, e:
		logging_util.debug('simpleplugin start error: {}'.format(e))
		return

	src = Queue(maxsize=1000)
	agentFacade.startEx(src)

	listenForever(src)

def writeTagCount(m, pcode, oid, now, oname):
	p = TagCountPack(category=m.name)
	p.pcode = pcode
	p.oid = oid
	p.time = now
	for field in m.fieldList():
		p.fields.put(field.key, whatapValue.toValue(field.value))
	for tag in m.tagList():
		p.tags.put(tag.key, whatapValue.toValue(tag.value))
	
	p.putTag("oname", whatapValue.toValue(oname))

	data.SendHide(p)

def writeLog(m, pcode, oid, now, oname):
	#print("simplePluginWrapper writeLog ", m, pcode, oid, now, oname)
	p = LogSinkPack(category=m.name)
	p.pcode = pcode
	p.oid = oid
	p.time = now
	if m.fieldList():
		for field in m.fieldList():
			p.fields.put(field.key, whatapValue.toValue(field.value))
	if m.tagList():
		for tag in m.tagList():
			p.tags.put(tag.key, whatapValue.toValue(tag.value))
		
	p.tags.put("oname", whatapValue.toValue(oname))
	p.content = m.content
	p.line = m.line

	

	data.SendHide(p)


def listenForever(src):
	secure.GetSecurityMaster().WaitForInit()
	while True:
		secu = secure.GetSecurityMaster()
		pcode = secu.pcode
		oid = secu.oid
		oname = secu.oname
		# if not config.GetConfig().IsExtensionEnabled:
		# 	continue
		m = src.get()
		
		if not m:
			time.sleep(1)
			continue 
		now = date_util.now()
		if m and isinstance(m, simpleplugin.LogMetric):
			try:
				writeLog(m, pcode, oid, now, oname)
			except Exception, e:
				logging_util.debug("simplepluginWrapper writeLog error:{}".format(e))
		elif m and isinstance(m, simpleplugin.Metric):
			try:
				writeTagCount(m, pcode, oid, now, oname)
			except Exception, e:
				logging_util.debug("simplepluginWrapper writeTagCount error:{}".format(e))
			