#!/usr/bin/env python


import urllib
import ee
import geojson  
from geopandas import GeoDataFrame
from shapely.geometry import shape

ee.Initialize()
   

def fc2df(fc):
    # Convert a FeatureCollection into a pandas DataFrame
    # Features is a list of dict with the output
    features = fc.getInfo()['features']

    dictarr = []
      
    for f in features:
        # Store all attributes in a dict
        attr = f['properties']
        # and treat geometry separately
        attr['geometry'] = f['geometry']  # GeoJSON Feature!
        # attr['geometrytype'] = f['geometry']['type']
        dictarr.append(attr)
       
    df = GeoDataFrame(dictarr)
    # Convert GeoJSON features to shape
    df['geometry'] = map(lambda s: shape(s), df.geometry)    
    return df

fc = ee.FeatureCollection('ft:1eHL58sc7FhFBjZGH0_wPivmz2rEQER3vQkklZJ_4')
tempdata = fc2df(fc)

tempdata2 = tempdata.to_json()
tempdat3 = geojson.loads(tempdata2)
regiontosave =tempdat3['features'][0]['geometry']['coordinates']

        


ImageCollectionV = "NOAA/CFSV2/FOR6H"
yearsS = "2001"
yearsE =   "2003"

    


startdate = str(yearsS) +'-01-01'
enddate =   str(yearsE)+'-01-01'
collection = (ee.ImageCollection(ImageCollectionV).filterDate(startdate,enddate))




images = collection.getInfo()['features']

			 

urls = []

for i in images:

     assetId = i['id']
    
     print assetId
     if assetId[25:27] == "12" :# we only need the 12:00 houer date
      print "yes"
      date_for_file_name =  "CFSV"+ assetId[17:28]
      imageLabel = assetId.split('/')[1]
      saveImage = ee.Image(assetId)
      path = saveImage.getDownloadUrl({'crs': 'EPSG:4326','region': regiontosave})
      testfile = urllib.URLopener()
      testfile.retrieve(path,date_for_file_name+".zip")
     else:
         print "skip file"
     
     
     
     

     
     


    