import os
import datetime
from ftplib import FTP

import numpy as np

from nansat import Nansat

from sadcat import L3PROC

class L3PROC_rs2ice(L3PROC):
    '''Methods for L3 processing of Radarsat ice/water classification:'''

    def export_ice(self, data, thrNameMask='./%s/%s%s.nc'):
        # get data from averaged nansat
        ice = data['ice']
        mask = data['mask']

        # modify ice values ( open_water ice_cover unclassified )
        ice[ice <= 0.5] = 0  # water
        ice[ice > 0.5] = 1   # ice
        ice[mask < 64] = 2   # clouds
        ice = ice.astype('int8')

        # modify mask values (0 - no_data, 1 - unclassified, 2 - land, 3 - nominal)
        mask[(mask > 2) * (mask <  64)] = 1
        mask[mask == 64] = 3
        mask = mask.astype('int8')

        # get lon/lat grids from domain
        lon, lat = data.get_geolocation_grids()

        iceData = Nansat(domain=data)
        iceData.add_bands([ice, mask, lon, lat], [{'name': 'ice'},
                                                  {'name': 'mask'},
                                                  {'name': 'lon'},
                                                  {'name': 'lat'}])
        iceData.vrt._set_time(data.get_time()[0])

        products = {
            'ice':  {'type': '>i1',
                     'standard_name': "sea_ice_classification",
                     'flag_values': np.byte([0, 1, 2]),
                     'long_name': 'sea ice type',
                     'flag_meanings': ' open_water ice_cover unclassified ',
                     'valid_range': [0, 2],
                     'grid_mapping': 'stereographic',
                     '_FillValue':  np.byte(2),
                     },
            'mask': {'type': '>i1',
                     'standard_name': 'sea_ice_classification status_flag',
                     'long_name': 'status flag for sea ice type retrieval',
                     'flag_values': np.byte([0, 1, 2, 3]),
                     'flag_meanings': ' no_data nonclassified land nominal ',
                     'valid_range': [0, 3],
                     'grid_mapping': 'stereographic',
                     '_FillValue':  np.byte(4),
                     },
            'lon':  {'type': '>f4',
                     'standard_name': 'longitude',
                     'long_name': 'longitude',
                     'units': 'degrees_east',
                     'grid_mapping': 'stereographic',
                     },
            'lat':  {'type': '>f4',
                     'standard_name': 'latitude',
                     'long_name': 'latitude',
                     'units': 'degrees_north',
                     'grid_mapping': 'stereographic',
                     },
            }

        metadata = iceData.get_metadata()
        metadata.pop('fileName')
        metadata.update({
            'title': 'Radarsat2 HH/HV based ice/water classification',
            'comment': 'The product contains daily-averaged maps of ice/water generated by the NERSC Radarsat2 ice/water classification algorithm ',
            'sensor': 'Radarsat2',
            'references': 'Alexandrov V, Zakhvatkina NY. Use of mathematical methods of image processing in interpretation of SAR images of sea ice. In: Smirnov V.G. Satellite methods of sea ice cover characteristics determination, Publisher:Paulsen, ISBN:9785987970652, 2011',
            'contact' : "anton.korosov@nersc.no",
            })

        status = self.export(iceData, thrNameMask, products, metadata)
        return status
