#!/usr/bin/python
# Nested day timelapse
# 2.10.2009 by Nick Fankhausers
import os,time,shutil,sys,psyco
psyco.full()
nframes=25*60
step=1 # in seconds
target_dir='/home/nyk/nom'
start_hour,end_hour=5,22
#path='/mnt/auto/nick/kg/%d.jpg'
path='/mnt/max/nick/kg/%d.jpg'

def get_file_list():
 rl=[]
# map_fn='/home/nyk/ideas/motion_detect_cache.py.log'
 map_fn='/root/bin/motion_detect_cache.py.log'
 for l in open(map_fn):
  lsp=l.strip().split('\t')
  if int(lsp[1])>5: continue
  rl.append(lsp[0].split('-'))
 return rl

def day_sec(x):
 s=time.strftime('%H:%M',time.gmtime(x))
 ss=map(int,s.split(':'))
 return ss[0]*3600+ss[1]*60

digits_only=lambda s : int(s.replace('.jpg',''))
hms=lambda x : time.strftime('%d.%m.%Y %H:%M:%S',time.gmtime(x+7200))
hour=lambda x : int(time.strftime('%H',time.gmtime(x+7200)))
is_day=lambda x : hour(x)>start_hour and hour(x)<end_hour
if not os.path.isdir(target_dir): os.mkdir(target_dir)
flist=get_file_list()
flist2=map(lambda x : x[1],flist)
flist2int=map(lambda x : digits_only(x),flist2)
t1,t2=min(flist2int),max(flist2int)
duration=t2-t1
duration_days=duration/(24*3600)
per_day=(nframes/duration_days)*2
print 'duration_days = %d, per_day = %d' % (duration_days,per_day)
d,dc,t0,j=20,0,t1-day_sec(t1),5*3600
tx=lambda x,y : t0+x*24*3600+y
while True:
 j+=step
 txdj=tx(d,j)
 while txdj<t2:
  for i in range(500):
   txdj=tx(d,j+i)
   if txdj in flist2int: j+=i; break
  if txdj in flist2int: break
  d+=1
  dc=0
 if txdj>t2: break
 if not is_day(txdj): continue
 print hms(txdj)
 shutil.copy(path%txdj,target_dir)
 dc+=1
 if dc==per_day: d+=1; dc=0