import asyncio
import os, sys
import argparse
import json

from sqlor.dbpools import DBPools
from appPublic.jsonConfig import getConfig
from appPublic.log import debug
from appPublic.dictObject import DictObject
from appPublic.timeUtils import curDateString, timestampstr
from appPublic.uniqueID import getID
from appPublic.folderUtils import listFile, _mkdir
from ahserver.filestorage import FileStorage

import av

def get_1st_keyframe(mloc, loctype,  userid):
	# Open the video file
	fs = FileStorage()
	if loctype == '0': # webpath
		mloc1 = fs.realPath(mloc)
		debug(f'{mloc=}, {mloc1=}')
		mloc = mloc1
	container = av.open(mloc)
	# Iterate through the video to find the first key frame
	kcnt = 0
	for frame in container.decode(video=0):
		if frame.key_frame:
			kcnt += 1
			if kcnt > 10:
				# Save the key frame as an image
				name = os.path.basename(mloc).split('.')[0] + '.jpg'
				fn = fs._name2path(name, userid=userid)
				webpath = fs.webpath(fn)
				_mkdir(os.path.dirname(fn))
				frame.to_image().save(fn)
				return webpath

async def gen_video_keyframe():
	db = DBPools()
	async with db.sqlorContext('mediadb') as sor:
		sql = "select * from media where mtype = 'video' and logo_url is null and mloctype in ('0', '1')"
		recs = await sor.sqlExe(sql, {})
		for r in recs:
			wp = get_1st_keyframe(r.mlocation, r.mloctype, r.ownerid)
			ns = {'id':r.id, 'logo_url':wp}
			await sor.U('media', ns)

async def main():
	parser = argparse.ArgumentParser(prog=sys.argv[0])
	parser.add_argument('-w', '--workdir')
	args = parser.parse_args()
	workdir = args.workdir or os.getcwd()
	config = getConfig(workdir, {'workdir':workdir})
	DBPools(config.databases)
	await gen_video_keyframe()

if __name__ == '__main__':
	loop = asyncio.new_event_loop()
	loop.run_until_complete(main())

