# -*- coding: iso-8859-1 -*-
#
# quakepy/pmc/PMCMetadata.py
# $Id: PMCMetadata.py 186 2009-03-31 22:23:33Z fab $
#
# The QuakePy package
# http://www.quakepy.org
#

############################################################################
#    Copyright (C) 2007-2009 by Fabian Euchner and Danijel Schorlemmer     #
#    fabian@fabian-euchner.de                                              #
#                                                                          #
#    This program is free software; you can redistribute it and#or modify  #
#    it under the terms of the GNU General Public License as published by  #
#    the Free Software Foundation; either version 2 of the License, or     #
#    (at your option) any later version.                                   #
#                                                                          #
#    This program is distributed in the hope that it will be useful,       #
#    but WITHOUT ANY WARRANTY; without even the implied warranty of        #
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         #
#    GNU General Public License for more details.                          #
#                                                                          #
#    You should have received a copy of the GNU General Public License     #
#    along with this program; if not, write to the                         #
#    Free Software Foundation, Inc.,                                       #
#    59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             #
############################################################################

"""
The QuakePy package
http://www.quakepy.org
"""

__version__  = '$Id: PMCMetadata.py 186 2009-03-31 22:23:33Z fab $'
__revision__ = '$Revision: 186 $'
__author__   = "Fabian Euchner <fabian@fabian-euchner.de>, Danijel Schorlemmer <ds@usc.edu>"
__license__  = "GPL"

import os
import glob
import re

from mx.DateTime import DateTimeType, TimeDelta

class PMCMetadata( object ):
    """
    all times used in this class are UTC
    """
    
    def __init__( self, **kwargs ):

        # init all variables to None or False
        self.useDate           = None
        self.startDate         = None
        self.endDate           = None

        self.timeZoneShift     = None

        self.runPath           = None
        self.pickInfoDir       = None
        self.distroDir         = None
        self.gridDir           = None

        self.pickInfoPlotDir   = None
        self.distroPlotDir     = None
        
        self.gridFilePrefix    = None

        self.catalogBaseDir          = None
        self.catalogFilesPattern     = None
        self.catalogFilesPerInterval = None
        
        self.catalogFilesAll     = []
        self.catalogFiles        = []

        self.stationfile         = None
        self.aliasfile           = None
        self.polygonfile         = None

        self.combinationsPickleFile = None
        self.useDistStyle           = None
        self.smoothDist             = None
        self.useMaxStationCnt       = None

        self.targetMagArray         = []
        self.targetProbArray        = []

        self.areaPolygon            = {}
        self.areaDepth              = []

        self.skipPickInfo      = False
        self.skipProbDistro    = False
        self.skipGrid          = False

        self.combinePickInfoProbDistro = False
        self.discardPickInfo           = False

        self.plotPickInfo              = False
        self.plotProbDistro            = False

        self.probDistroColorMapFile    = None

    def getCatalogFilesAll( self ):

        if (     self.catalogBaseDir is not None and len( self.catalogBaseDir ) > 0
             and self.catalogFilesPattern is not None and len( self.catalogFilesPattern ) > 0 ):
            self.catalogFilesAll = sorted( glob.glob( os.path.join( self.catalogBaseDir, self.catalogFilesPattern ) ) )

    def getCatalogFiles( self ):

        self.getCatalogFilesAll()

        if self.timeZoneShift is None:
            raise ValueError, "PMCMetadata:getCatalogFiles() - timeZoneShift has to be set before calling getCatalogFiles()"
         
        # startDate and endDate have to be mxDateTime.DateTimeType
        if (     ( self.startDate is not None )
             and ( self.endDate is not None )
             and isinstance( self.startDate, DateTimeType )
             and isinstance( self.endDate, DateTimeType ) ):

            localStartDate = self.startDate + TimeDelta( self.timeZoneShift )
            localEndDate   = self.endDate + TimeDelta( self.timeZoneShift )
            
            # loop over years from startDate to endDate
            # Note: this is done with local time, so that it matches
            # the local year/month designations in catalog file names
            for time_year in xrange( localStartDate.year, localEndDate.year + 1 ):
                
                # get catfiles for time period
                for curr_catfile in self.catalogFilesAll:

                    datecode      = re.match( r'^.+(\d{6})_[ABC].deck.Z.bz2$', curr_catfile )
                    yearmonth_str = str( datecode.group(1) )
                    year          = int( yearmonth_str[0:4] )
                    month         = int( yearmonth_str[4:6] ) 

                    if ( year == time_year ):

                        if not (    ( year == localStartDate.year and month < localStartDate.month )
                                 or ( year == localEndDate.year and month > localEndDate.month ) ):
                        
                            self.catalogFiles.append( curr_catfile )
                            print " PMCMetadata: added catalog file %s to current catalog" % curr_catfile
                    

