import appuifw
import camera
import graphics
import e32
import audio

#Some source code from: http://www.bigbold.com/snippets/tag/camera

def save_a_copy(ima):

    global num_foto
    
    name = u'move' + str(num_foto) + u'.png'
    ima.save('e:\\' + name)
    num_foto = num_foto + 1

def getdata(im, bpp=24):
    import struct, zlib
    im.save('C:\\pixels.png', bpp=bpp, compression='no')
    f = open('C:\\pixels.png', 'rb')
    f.seek(8 +8+13+4)
    chunk = []
    while 1:
        n = struct.unpack('>L', f.read(4))[0]
        if n==0: break  # 'IEND' chunk
        f.read(4) # 'IDAT'
        chunk.append(f.read(n))
        f.read(4)   # CRC
    f.close()
    return zlib.decompress(''.join(chunk))  # '\x00' prefix each line


def exit_key_handler():
    app_lock.signal()

def p_stop():

    global running
    running = 0

def pix_threshold():

    global pixthreshold
    pixthreshold = appuifw.query(u"Value pixel threshold 0-256", "number",pixthreshold)

def img_threshold():

    global imgthreshold
    imgthreshold = appuifw.query(u"Value image threshold 0-900", "number",imgthreshold)

appuifw.app.screen='normal'

texto = appuifw.Text()

texto.clear()

texto.add(u'Welcome to MvDetecion 0.1\n')
texto.add(u'Developed by Ignacio Lopez\n')

appuifw.app.body = texto

appuifw.app.menu = [(u"Stop",p_stop),(u'pix threshold',pix_threshold),(u'img threshold',img_threshold)]


appuifw.app.title = u"MvDetection 0.1"

app_lock = e32.Ao_lock()

appuifw.app.exit_key_handler = exit_key_handler

running = 1

pixthreshold = 10
imgthreshold = 45

firsttime = 1;
num = 0

detected = 0

num_foto = 0

last1 = '\x00' * 930    # can be anything
while running:
    im = camera.take_photo('RGB', (160,120))
  
    num = num + 1

    data = getdata(im,8)

    if (firsttime == 1):
        last1=data
        firsttime=0
        texto.add(u'La primera foto\n')
    # check difference for motion
    pixdiff = 0
    # texto.add(u'len data:' + str(len(data)) + u'\n')
    for i in range(len(data)):
        if abs(ord(data[i])-ord(last1[i])) > pixthreshold:  # pix threshold 15/256
            # texto.add(u'Un pix diferente')
            pixdiff += 1
            if pixdiff > imgthreshold:    # img threshold 90/900
                #im.rectangle([(10,10),(40,40)], fill=0xff0000)  # fill
                texto.add(u'Movement detected\n')
                s = audio.Sound.open(u'e:\\Sounds\chimes.wav') #This file must exists
                detected = 1
                s.play()
                save_a_copy(im)
                break           # motion detected

    if (detected == 0 ):
        texto.add(u'NO movement detected\n')

    detected = 0
    last1 = data
    #c.blit(im, (0,0), (8,12))   # show camera
    #miso.reset_inactivity_time()



app_lock.wait()

