import json,subprocess,sys,time
from lib import *
ep=int(sys.argv[1]); factor=sys.argv[2]
time.sleep(float(sys.argv[3]) if len(sys.argv)>3 else 0)
b('ActivateWindow(Home)',300); b('SetFocus(9000,2)',1500); b('SetFocus(30200,0)',900)
names=info(*['Container(30200).ListItemAbsolute(%d).Label'%i for i in range(7)])
idx=[i for i in range(7) if 'Krok' in names['Container(30200).ListItemAbsolute(%d).Label'%i]][0]
b('SetFocus(30200,%d)'%idx,800)
detail=info('Container(30200).ListItem.Property(milionar.hero.b2)')['Container(30200).ListItem.Property(milionar.hero.b2)']
th=subprocess.Popen([sys.executable,HERE+'/throttle.py',factor]); time.sleep(1)
t=time.time(); b(detail,100)
while not info('Window(Home).Property(milionar.detail.active)').get('Window(Home).Property(milionar.detail.active)'): time.sleep(.1)
print('detail opened in',round(time.time()-t,2))
t=time.time()
while True:
    r=info('Container(41100).NumItems','Container(41300).NumItems','Container(41500).NumItems')
    if all(int(v or 0)>0 for k,v in r.items() if '41100' in k or '41300' in k): break
    time.sleep(.1)
    if time.time()-t>20: break
print('rows there',round(time.time()-t,2),r)
time.sleep(3); b('SetFocus(41100,0)',1500); b('Action(Select)',4000); b('SetFocus(41200,%d)'%(ep-1),2500)
mov=HERE+'/perf/mark.mov'
if os.path.exists(mov): os.remove(mov)
rec=subprocess.Popen(['screencapture','-x','-v','-V','24',mov],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
time.sleep(3)
do({'op':'mark','token':'SCN-NOW'})
b('NotifyAll(plugin.video.milionar,run:RunPlugin(plugin://plugin.video.milionar/?action=ctx_mark&type=episode&tmdb=2617&s=1&e=%d&watched=1))'%ep,100)
time.sleep(19.5)
do({'op':'mark','token':'SCN-END'})
rec.wait(); th.terminate(); th.wait(); subprocess.run(['pkill','-CONT','-x','Kodi'])
json.dump([3.0],open(HERE+'/perf/mark.json','w'))
