#!/usr/bin/env python
__author__    = 'Kurt Schwehr'
__version__   = '$Revision: 8608 $'.split()[1]
__date__      = '$Date: 2008-02-10 17:54:09 -0500 (Sun, 10 Feb 2008) $'.split()[1]
__copyright__ = '2008'
__license__   = 'GPL v2'
__contact__   = 'kurt at ccom.unh.edu'
__doc__='''
Rebuild the cache tables for high speed access to the current vessel
traffic status.  This works on the last_position and track_lines 
tables.

@requires: U{magicdate<http://cheeseshop.python.org/pypi/magicdate>}

@status: under development
@undocumented:  __doc__ parser
@since: 2008-Jan-23
@status: Needs sqlite support
@todo: make this work with any database (sqlite3)
@organization: U{CCOM<http://ccom.unh.edu/>}
'''

import sys
import datetime
import time

import magicdate

import aisutils.database
import aisutils.uscg


######################################################################


if __name__=='__main__':
    from optparse import OptionParser

    # FIX: is importing __init__ safe?
    parser = OptionParser(usage="%prog [options]"
                          ,version="%prog "+__version__ + " ("+__date__+")"
                          ,option_class=magicdate.MagicDateOption
                          )

    aisutils.database.stdCmdlineOptions(parser,'postgres')

    parser.add_option('-l','--limit-points',dest='limitPoints',type='int'
                      ,default=10
                      ,help='Max number of points for a ship track [default: %default]')

    parser.add_option('-n','--no-limit-points',dest='limitPoints'
                      ,action='store_const'
                      ,const=None
                      ,help='Make points unlimited')

    parser.add_option('-v','--verbose',dest='verbose',default=False,action='store_true'
                      ,help='Make the test output verbose')


    parser.add_option('-a','--all',dest='updateAll',default=False,action='store_true'
                      ,help='Update all the cache tables')

    parser.add_option('-T','--track-lines',dest='updateTrackLines',default=False,action='store_true'
                      ,help='Update the track_lines table')

    parser.add_option('-L','--last-position',dest='updateLastPosition',default=False,action='store_true'
                      ,help='Update the last_position table')


    parser.add_option('--time-limit-all',dest='timeLimitAll',type='magicdate'
                      ,default=None
                      , help='Limit all caches by one magic date time (e.g. "1 hour ago")'
                      +'-s and -S override this'
                      +' [default %default]')

    parser.add_option('-s','--track-start-time',dest='track_start',type='magicdate',default=None
                      ,help='magicdate - Oldest allowable time for a track line [default %default]')

    parser.add_option('-S','--last-position-start-time',dest='last_position_start',type='magicdate',default=None
                      ,help='magicdate - Oldest allowable time for a last position [default %default]')

    (options,args) = parser.parse_args()
    v = options.verbose

    if options.timeLimitAll is not None:
        when = datetime.datetime.now() - datetime.timedelta(hours=options.timeLimitAll)
        if options.track_start == None:
            options.track_start = when
        if options.last_position_start == None:
            options.last_position_start = when

    if type(options.last_position_start) is datetime.date:
        d = options.last_position_start
        options.last_position_start = datetime.datetime(d.year, d.month, d.day)

    if v:
        print 'time constraints', options.track_start,  options.last_position_start

    if options.updateAll:
        options.updateTrackLines=True
        options.updateLastPosition=True

    options.uscg=True # FIX: don't hack this in
    options.dbType = 'postgres' # FIX: don't force this

    cx = aisutils.database.connect(options,dbType=options.dbType)

    tzoffset = datetime.timedelta(seconds=time.timezone) # to get to UTC from magicdate's local datetime

    if options.updateTrackLines:

        startTime = options.track_start + tzoffset
        
        if v:
            sys.stderr.write('Updating track_lines (%s to %s)\n' % (startTime,datetime.datetime.utcnow()))

        
        aisutils.database.rebuild_track_lines(cx,limitPoints=options.limitPoints, startTime = startTime, verbose = v)

    if options.updateLastPosition:

        startTime = options.last_position_start + tzoffset

        if v:
            sys.stderr.write('\nUpdating last_position (%s to %s)\n' % (startTime,datetime.datetime.utcnow()))

        aisutils.database.rebuild_last_position(cx, startTime = startTime, verbose = v)

