#! /usr/bin/env python

import sys, argparse, os.path
import cvutils, utils, moving
from metadata import createDatabase, Site, VideoSequence
from datetime import datetime, timedelta

parser = argparse.ArgumentParser(description='The program merges feature trajectories recorded from the same site synchronously between start and end time.')
parser.add_argument('-i', dest = 'metadataFilename', help = 'name of the metadata file', required = True)
parser.add_argument('-n', dest = 'siteId', help = 'site id or site name', required = True)
parser.add_argument('--t1', dest = 'startTime', help = 'time to start merging features (format %Y-%m-%d %H:%M:%S, eg 2011-06-22 10:00:39)') # if not provided, take common time interval
parser.add_argument('--t2', dest = 'endTime', help = 'time to stop merging features (format %Y-%m-%d %H:%M:%S, eg 2011-06-22 10:00:39)')

args = parser.parse_args()

session = createDatabase(args.metadataFilename)

site = Site.getSite(session, args.siteId)
if site is None:
    print('Site {} was not found in {}. Exiting'.format(args.siteId, args.metadataFilename))
    sys.exit()
else:
    site = site[0]

startTime = datetime.strptime(args.startTime, utils.datetimeFormat)
endTime = datetime.strptime(args.endTime, utils.datetimeFormat)
processInterval = moving.TimeInterval(startTime, endTime)
videoSequences = session.query(VideoSequence).filter(VideoSequence.site == site).order_by(VideoSequence.startTime.asc()).all() #.order_by(VideoSequence.cameraViewIdx) .filter(VideoSequence.startTime <= startTime)
#timeIntervals = [v.intersection(startTime, endTime) for v in videoSequences]

cameraViews = set([v.cameraView for v in videoSequences])

videoSequences = {cv: [v for v in videoSequences if v.cameraView == cv] for cv in cameraViews}
timeIntervals = {}
for cv in videoSequences:
    timeIntervals[cv] = moving.TimeInterval.unionIntervals([v.getTimeInterval() for v in videoSequences[cv]])

commonTimeInterval = timeIntervals.values()[0]
for inter in timeIntervals.values()[1:]:
    commonTimeInterval = moving.TimeInterval.intersection(commonTimeInterval, inter)
commonTimeInterval = moving.TimeInterval.intersection(commonTimeInterval, processInterval)

# for all camera view, for all video, select from positions and velocities where frame_number is in the right range and insert in new database

# should we save the information of the new "sequence" in the metadata?
#session.add(VideoSequence('merged', , timedelta(seconds = 31616./30.), laurierSite, laurierCameraViewSpot0))

#session.commit()
