# Path: nansat/nsr.py
# class NSR(osr.SpatialReference, object):
#     """Nansat Spatial Reference. Overrides constructor of osr.SpatialReference.
# 
#     Parameters
#     ----------
#     srs : 0, PROJ4 or EPSG or WKT or osr.SpatialReference, NSR
#         Specifies spatial reference system (SRS)
#         PROJ4:
#         string with proj4 options [http://trac.osgeo.org/proj/] e.g.:
#         '+proj=latlong +datum=WGS84 +ellps=WGS84 +no_defs'
#         '+proj=stere +datum=WGS84 +ellps=WGS84 +lat_0=75 +lon_0=0 +no_defs'
#         EPSG:
#         integer with EPSG number, [http://spatialreference.org/],
#         e.g. 4326
#         WKT:
#         string with Well Know Text of SRS. E.g.:
#         'GEOGCS["WGS 84",
#             DATUM["WGS_1984",
#                 SPHEROID["WGS 84",6378137,298.257223563,
#                     AUTHORITY["EPSG","7030"]],
#                 TOWGS84[0,0,0,0,0,0,0],
#                 AUTHORITY["EPSG","6326"]],
#             PRIMEM["Greenwich",0,
#                 AUTHORITY["EPSG","8901"]],
#             UNIT["degree",0.0174532925199433,
#                 AUTHORITY["EPSG","9108"]],
#             AUTHORITY["EPSG","4326"]]'
# 
#     """
# 
#     def __init__(self, srs=0):
#         """Create Spatial Reference System from input parameter"""
#         if sys.version_info.major == 2:
#             str_types = (str, unicode)
#         else:
#             str_types = str
#         # create SRS
#         osr.SpatialReference.__init__(self)
# 
#         # parse input parameters
#         status = 1
#         if srs is 0:
#             # generate default WGS84 SRS
#             status = self.ImportFromEPSG(4326)
#         elif isinstance(srs, str_types):
#             # parse as proj4 string
#             status = self.ImportFromProj4(str(srs))
#             if status > 0:
#                 # parse as WKT string
#                 status = self.ImportFromWkt(str(srs))
#             if status > 0:
#                 raise NansatProjectionError('Proj4 or WKT (%s) is wrong' % srs)
#         elif isinstance(srs, int):
#             # parse as EPSG code
#             status = self.ImportFromEPSG(srs)
#             if status > 0:
#                 raise NansatProjectionError('EPSG %d is wrong' % srs)
#         elif type(srs) in [osr.SpatialReference, NSR]:
#             # parse from input Spatial Reference
#             status = self.ImportFromWkt(srs.ExportToWkt())
#             if status > 0:
#                 raise NansatProjectionError('NSR %s is wrong' % srs)
# 
#     @property
#     def wkt(self):
#         """Well Known Text representation of SRS"""
#         return self.ExportToWkt()
# 
# Path: nansat/mappers/opendap.py
# class Opendap(VRT):
#     P2S = {
#         'H': 60*60,
#         'D': 86400,
#         'M': 30*24*60*60,
#         'Y': 31536000,
#         }
#     def test_mapper(self, filename):
#     def get_dataset(self, ds):
#     def get_geospatial_variable_names(self):
#     def get_dataset_time(self):
#     def get_layer_datetime(date, datetimes):
#     def get_metaitem(self, url, var_name, var_dimensions):
#     def _fix_encoding(var):
#     def create_vrt(self, filename, gdalDataset, gdalMetadata, date, ds, bands, cachedir):
#     def _filter_dimensions(self, dim_name):
#     def create_metadict(self, filename, var_names, time_id):
#     def get_time_coverage_resolution(self):
#     def get_shape(self):
#     def get_geotransform(self):


import os
import json
import numpy as np
import datetime as dt
import pythesint as pti
from nansat.nsr import NSR
from nansat.mappers.opendap import Dataset, Opendap
# http://thredds.met.no/thredds/dodsC/osisaf/met.no/ice/edge/2016/04/ice_edge_nh_polstere-100_multi_201604241200.nc ice_edge
# http://thredds.met.no/thredds/dodsC/osisaf_test/met.no/ice/drift_lr/merged/2013/09/ice_drift_nh_polstere-625_multi-oi_201309171200-201309191200.nc dX dY


class Mapper(Opendap):
    ''' VRT with mapping of WKV for NCEP GFS '''
    baseURLs = ['http://thredds.met.no/thredds/dodsC/cryoclim/met.no/osisaf-nh',
                'http://thredds.met.no/thredds/dodsC/osisaf_test/met.no/ice/',
                'http://thredds.met.no/thredds/dodsC/osisaf/met.no/ice/']
    timeVarName = 'time'
    xName = 'xc'
    yName = 'yc'
    t0 = dt.datetime(1978, 1, 1)
    srcDSProjection = NSR().wkt

    def __init__(self, filename, gdalDataset, gdalMetadata, date=None, ds=None, bands=None,
                 cachedir=None, **kwargs):
        ''' Create NCEP VRT
        Parameters:
            filename : URL
            date : str
                2010-05-01
            ds : netCDF.Dataset
                previously opened dataset

        '''
        self.test_mapper(filename)
        ds = Dataset(filename)
        proj4str = '%s +units=%s' % (ds.variables['Polar_Stereographic_Grid'].proj4_string,
                                     ds.variables['xc'].units)

# Path: nansat/nsr.py
# class NSR(osr.SpatialReference, object):
#     """Nansat Spatial Reference. Overrides constructor of osr.SpatialReference.
# 
#     Parameters
#     ----------
#     srs : 0, PROJ4 or EPSG or WKT or osr.SpatialReference, NSR
#         Specifies spatial reference system (SRS)
#         PROJ4:
#         string with proj4 options [http://trac.osgeo.org/proj/] e.g.:
#         '+proj=latlong +datum=WGS84 +ellps=WGS84 +no_defs'
#         '+proj=stere +datum=WGS84 +ellps=WGS84 +lat_0=75 +lon_0=0 +no_defs'
#         EPSG:
#         integer with EPSG number, [http://spatialreference.org/],
#         e.g. 4326
#         WKT:
#         string with Well Know Text of SRS. E.g.:
#         'GEOGCS["WGS 84",
#             DATUM["WGS_1984",
#                 SPHEROID["WGS 84",6378137,298.257223563,
#                     AUTHORITY["EPSG","7030"]],
#                 TOWGS84[0,0,0,0,0,0,0],
#                 AUTHORITY["EPSG","6326"]],
#             PRIMEM["Greenwich",0,
#                 AUTHORITY["EPSG","8901"]],
#             UNIT["degree",0.0174532925199433,
#                 AUTHORITY["EPSG","9108"]],
#             AUTHORITY["EPSG","4326"]]'
# 
#     """
# 
#     def __init__(self, srs=0):
#         """Create Spatial Reference System from input parameter"""
#         if sys.version_info.major == 2:
#             str_types = (str, unicode)
#         else:
#             str_types = str
#         # create SRS
#         osr.SpatialReference.__init__(self)
# 
#         # parse input parameters
#         status = 1
#         if srs is 0:
#             # generate default WGS84 SRS
#             status = self.ImportFromEPSG(4326)
#         elif isinstance(srs, str_types):
#             # parse as proj4 string
#             status = self.ImportFromProj4(str(srs))
#             if status > 0:
#                 # parse as WKT string
#                 status = self.ImportFromWkt(str(srs))
#             if status > 0:
#                 raise NansatProjectionError('Proj4 or WKT (%s) is wrong' % srs)
#         elif isinstance(srs, int):
#             # parse as EPSG code
#             status = self.ImportFromEPSG(srs)
#             if status > 0:
#                 raise NansatProjectionError('EPSG %d is wrong' % srs)
#         elif type(srs) in [osr.SpatialReference, NSR]:
#             # parse from input Spatial Reference
#             status = self.ImportFromWkt(srs.ExportToWkt())
#             if status > 0:
#                 raise NansatProjectionError('NSR %s is wrong' % srs)
# 
#     @property
#     def wkt(self):
#         """Well Known Text representation of SRS"""
#         return self.ExportToWkt()
# 
# Path: nansat/mappers/opendap.py
# class Opendap(VRT):
#     P2S = {
#         'H': 60*60,
#         'D': 86400,
#         'M': 30*24*60*60,
#         'Y': 31536000,
#         }
#     def test_mapper(self, filename):
#     def get_dataset(self, ds):
#     def get_geospatial_variable_names(self):
#     def get_dataset_time(self):
#     def get_layer_datetime(date, datetimes):
#     def get_metaitem(self, url, var_name, var_dimensions):
#     def _fix_encoding(var):
#     def create_vrt(self, filename, gdalDataset, gdalMetadata, date, ds, bands, cachedir):
#     def _filter_dimensions(self, dim_name):
#     def create_metadict(self, filename, var_names, time_id):
#     def get_time_coverage_resolution(self):
#     def get_shape(self):
#     def get_geotransform(self):


# Path: nansat/mappers/mapper_opendap_osisaf.py
import os
import json
import numpy as np
import datetime as dt
import pythesint as pti
from nansat.nsr import NSR
from nansat.mappers.opendap import Dataset, Opendap

# http://thredds.met.no/thredds/dodsC/osisaf/met.no/ice/edge/2016/04/ice_edge_nh_polstere-100_multi_201604241200.nc ice_edge
# http://thredds.met.no/thredds/dodsC/osisaf_test/met.no/ice/drift_lr/merged/2013/09/ice_drift_nh_polstere-625_multi-oi_201309171200-201309191200.nc dX dY


class Mapper(Opendap):
    ''' VRT with mapping of WKV for NCEP GFS '''
    baseURLs = ['http://thredds.met.no/thredds/dodsC/cryoclim/met.no/osisaf-nh',
                'http://thredds.met.no/thredds/dodsC/osisaf_test/met.no/ice/',
                'http://thredds.met.no/thredds/dodsC/osisaf/met.no/ice/']
    timeVarName = 'time'
    xName = 'xc'
    yName = 'yc'
    t0 = dt.datetime(1978, 1, 1)
    srcDSProjection = NSR().wkt

    def __init__(self, filename, gdalDataset, gdalMetadata, date=None, ds=None, bands=None,
                 cachedir=None, **kwargs):
        ''' Create NCEP VRT
        Parameters:
            filename : URL
            date : str
                2010-05-01
            ds : netCDF.Dataset
                previously opened dataset

        '''
        self.test_mapper(filename)
        ds = Dataset(filename)
        proj4str = '%s +units=%s' % (ds.variables['Polar_Stereographic_Grid'].proj4_string,
                                     ds.variables['xc'].units)

        self.srcDSProjection = NSR(proj4str).wkt