import os
import codecs
import json
from traceback import format_exc
from appPublic.log import debug, error, exception
from appPublic.myTE import MyTemplateEngine
from appPublic.folderUtils import temp_file
from sqlor.dbpools import DBPools
from ahserver.serverenv import get_serverenv
from .getdbname import get_dbname
from .hostdev import hostdev_node

async def get_service_params_form(serviceid):
	dbname = get_dbname()
	db = DBPools()
	async with db.sqlorContext(dbname) as sor:
		servs = await sor.R('techservice', {'id':serviceid})
		if len(servs) == 0:
			e = Exception(f'techservice has not service with {serviceid=}')
			exception(f'{e},{format_exc()}')
		serv = servs[0]
		fui = json.loads(serv.params_ui)
		fui.fields.append({
			'name':'serviceid',
			'uitype':'hide',
			'value':service
		})
		return fui
	
async def service4host(serviceid, hostid, parmas):
	userinfos = {k:v for k,v in params.items() if k in ['userid', 'userorgid']}
	params = {k:v for k,v in params.items() if k not in ['userid', 'userorgid']}
	te = MyTemplateEngine(['.'])
	dbname = get_dbname()
	db = DBPools()
	async with db.sqlorContext(dbname) as sor:
		servs = await sor.R('techservice', {'id':serviceid})
		if len(servs) == 0:
			e = Exception(f'techservice has not service with {serviceid=}')
			exception(f'{e},{format_exc()}')
		serv = servs[0]
		script =  te.renders(serv.script, params)
		tmpf = temp_file(subffix='.sh')
		with codecs.open(tmpf, 'w', 'utf-8') as f:
			f.write(script)
		node = await hostdev_node(hostid)
		async with node.get_connector() as conn:
			cmd = f'/tmp/{os.path.basename(tmpf)}'
			await conn.l2r(tmpf, cmd)
			await conn.run(f'chmod +x {cmd}')
			x = await conn.run(f'bash {cmd}')
			debug(f'{x.output=}')
