#! /usr/bin/env python

import sys,getopt

import storage
import cvutils
from utils import FakeSecHead

from numpy.linalg.linalg import inv
from numpy import loadtxt
from ConfigParser import ConfigParser

options, args = getopt.getopt(sys.argv[1:], 'hi:d:t:o:f:',['help']) 
# alternative long names are a pain to support ,'video-filename=','database-filename=', 'type='

options = dict(options)

print options, args

if '--help' in options.keys() or '-h' in options.keys() or len(sys.argv) == 1:
    print('Usage: '+sys.argv[0]+' --help|-h -i video-filename -d database-filename [-t object_type] [-o image2world_homography] [-f first_frame]\n'
          +'Or   : '+sys.argv[0]+' [-t object_type] config_file.cfg\n\n'
          'Order matters between positional and named arguments\n'
          'object_type can be feature or object')
    sys.exit()

objectType = 'feature'
if '-t' in options.keys():
    objectType = options['-t']

if len(args)>0: # consider there is a configuration file
    config = ConfigParser()
    config.readfp(FakeSecHead(open(args[0])))
    sectionHeader = config.sections()[0]
    videoFilename = config.get(sectionHeader, 'video-filename')
    databaseFilename = config.get(sectionHeader, 'database-filename')
    homography = inv(loadtxt(config.get(sectionHeader, 'homography-filename')))
    firstFrameNum = config.getint(sectionHeader, 'frame1')
else:
    videoFilename = options['-i']
    databaseFilename = options['-d']
    homography = None
    if '-o' in options.keys():
        homography = inv(loadtxt(options['-o']))            
    firstFrameNum = 0
    if '-f' in options.keys():
        firstFrameNum = int(options['-f'])

objects = storage.loadTrajectoriesFromSqlite(databaseFilename, objectType)
cvutils.displayTrajectories(videoFilename, objects, homography, firstFrameNum)
