#!/usr/bin/python
from __future__ import print_function

from PIL import Image

import tkinter
from fsdk import FSDK
from tk import MainWindow, Style

print("Initializing FSDK... ", end='')
FSDK.ActivateLibrary(""); 
FSDK.Initialize()
print("OK\nLicense info:", FSDK.GetLicenseInfo())

FSDK.InitializeCapturing()
print('Looking for video cameras... ', end = '')
camList = FSDK.ListCameraNames()

if not camList:
    print("Please attach a camera."); 
    quit(1)

print(camList[0].devicePath)

camera = camList[0] # choose the first camera (0)
print("using '%s'" % camera)
formatList = FSDK.ListVideoFormats(camera)
print(*formatList, sep='\n')

vfmt = formatList[0] # choose the first format: vfmt.Width, vfmt.Height, vfmt.BPP
print('Selected camera format:', vfmt)
FSDK.SetVideoFormat(camera, vfmt)

print("Trying to open '%s'... " % camera, end = '')
camera = FSDK.OpenVideoCamera(camera)
print("OK", camera.handle)


fsdkTracker = FSDK.Tracker()  # creating a FSDK Tracker 

fsdkTracker.SetParameters( # set realtime face detection parameters
    RecognizeFaces=False, DetectFacialFeatures=True,
    InternalResizeWidth=256, FaceDetectionThreshold=5,
)

need_to_exit = False

def onDestroy():
    global need_to_exit
    need_to_exit = True

root = tkinter.Tk()
root.title('Live Recognition')
root.protocol("WM_DELETE_WINDOW", onDestroy)

window = MainWindow(root)

featureStyle = Style(color='#FFFF60', width=2, fill='#FFFF60')
features = []

while not need_to_exit:
    for i in features:
        window.deleteObject(i)

    features = []

    img = camera.GrabFrame()
    img = img.Resize(window.getScaleFor(img.width, img.height))
    window.drawImage(Image.frombytes('RGB', (img.width, img.height), img.ToBytes(FSDK.FSDK_IMAGE_COLOR_24BIT)))

    for face_id in fsdkTracker.FeedFrame(0, img):
        features.extend(window.drawCircle((p.x, p.y), 1, style=featureStyle) for p in fsdkTracker.GetFacialFeatures(0, face_id))

    img.Free()

    window.update_idletasks()
    window.update()

root.destroy()

fsdkTracker.Free()
camera.Close()

FSDK.FinalizeCapturing()

FSDK.Finalize()
