# Copyright (C) 2013-2016 Martin Vejmelka, CU Denver
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
# of the Software, and to permit persons to whom the Software is furnished to do
# so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
# INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR
# A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

from __future__ import absolute_import
from __future__ import print_function
import pygrib
import numpy as np
import logging

def grib_messages(path,print_messages=False,max_messages=9999):
    """
    Compute the number of messages in grib file 
    :param path: path to the file
    :return: numeb of messages
    """
    grbf = pygrib.open(path)
    grbf.seek(0)
    i=0
    for grb in grbf:
        i=i+1
        if print_messages:
            logging.info('%s: %s' % (i, str(grb)))
        if i > max_messages:
            break
    grbf.seek(0)
    return i
   
def grib_valid_date(path): 
    """
    Look at validDate in a grib file 
    :param path: path to the file
    :return: valid date in datetime format
    """
    grbf = pygrib.open(path)
    if grbf.messages:
        if grbf.message(1).has_key('validDate'):
            return grbf.message(1).validDate
    return None

class GribFile(object):
    """
    Represents the content of one GRIB file.
    """

    def __init__(self, path, def_msg = 1):
        """
        Initializes metadata information.

        :param path: path to the file
        :param def_msg: the default message to process
        """
        self.path = path
        logging.info('Reading grib file %s' % path)
        self.grbf = pygrib.open(path)
        
    
    def __getitem__(self, msg_id):