import os
import time
import re

import numpy as np

from nansat import *
from radarsat2ice import Radarsat2Ice

class Radarsat2ImageIce(Nansat):
    '''
    Open files with RS2 classification results
    '''
    def __init__(self, fileName, logLevel=30):
        ''' Use generic mapper for opening the file'''
        Nansat.__init__(self, str(fileName), mapperName='generic', logLevel=logLevel);


class Radarsat2Image(Radarsat2Ice):
    '''
    Read parameters from RADARSAT2 file
    '''

    def __init__(self, fileName, logLevel=20):
        '''
        Read attributes from file name
        RS2_20110430_145008_0008_F1_HHHV_SGF_130933_4554_5368385
        Set values to the dictionary data
        '''
        Nansat.__init__(self, str(fileName), mapperName='radarsat2', logLevel=logLevel);

        #set values to the attribute data where it is availabe fro ImagesCatalog
        self.set_metadata('name',         "'%s'" % self.name)
        self.set_metadata('path',         "'%s'"   % self.path)
        self.set_metadata('sensor',       "'radarsat2'")
        self.set_metadata('sensstart',    "'%s'" % self.get_time()[0].strftime('%Y-%m-%d %H:%M:%S.%f'))
        self.set_metadata('polarization', "'%s'" % ''.join(re.findall('([H,V][H,V])?', self.fileName)))
        self.set_metadata('border',   self.get_border_postgis())

    def process_web(self, opts=None):
        '''
        NRT Processing of Radarsat includes:
            Visualisation of small quick look
            Visualisation of large quick look
            Generating map
        Input:
        ------
        opts: dictionary with processing options
        '''
        status = 1
        oBaseFileName = self.get_metadata('name').strip('"').strip("'")
        # 1. Generate small quicklook
        quicklookName = opts['mapDir'] + '/' + oBaseFileName + '_.jpg'
        if not os.path.exists(quicklookName):
            self.logger.info('quicklook: %s' % quicklookName)
            self.resize(width=300)
            self.write_figure(quicklookName, clim='hist', ratio=0.9, cmapName='gray')
            self.resize()
            status = 0


        # 2. Generate large quicklook
        quicklookName = opts['mapDir'] + '/large/' + oBaseFileName + '_.jpg'
        if not os.path.exists(quicklookName):
            self.logger.info('quicklook large: %s' % quicklookName)
            self.resize(width=600)
            lon, lat = self.get_geolocation_grids()
            self.write_figure(quicklookName,
                                        latGrid=lat, lonGrid=lon,
                                        nGridLines=6,  latlonLabels=6,
                                        clim='hist', ratio=0.9, cmapName='gray')
            self.resize()
            status = 0

        # 3. Generate map
        mapName = opts['mapDir'] + oBaseFileName + '_.png'
        if not os.path.exists(mapName):
            self.logger.info('map: %s' % quicklookName)
            self.write_map(mapName)
            status = 0

        # TMP:
        status = 0
        return status

    def process_ice(self, opts):
        '''Ice / Water classification:
        Use GLCM_NN and:
            Calculate textures (texture feature, TF)
            Process textures with neural network
            Generate map of Ice
            Save map to GTIF
        '''
        self.logger.info('Starting Radarsat2Image Ice processing')
        oBaseFileName = self.get_metadata('name').strip('"').strip("'")

        # get config values
        oDir = opts['oDir']

        #names of generated files
        resultName = oDir + oBaseFileName + '_.tif'
        icemapName = oDir + oBaseFileName + '_icemap.png'

        # 1. perform ice classification if file with result does not exist
        if not os.path.exists(resultName):
            self.logger.info('Generating %s' % resultName)

            # get cover type
            # 0 - non-class
            # 1 - land
            # 2 - fast ice (new SVM)
            # 3 - ice
            # 4 - edge
            # 5 - calm
            # 6 - rough1
            # 7 - rough2
            icemap = self.get_ice_map(glcmStep=opts['step'], threads=opts['threads'])

            # make map of ice
            ice = np.zeros(icemap.shape, 'uint8')
            ice[icemap == 2] = 1
            ice[icemap == 3] = 1
            ice[icemap == 4] = 1

            # make mask
            mask = np.zeros(icemap.shape, 'uint8') + 64
            mask[icemap == 0] = 1
            mask[icemap == 1] = 2

            # erase lower right nr pixel border
            nr = -4
            icemap[:, nr:] = 0
            icemap[nr:, :] = 0
            ice[:, nr:] = 0
            ice[nr:, :] = 0
            mask[:, nr:] = 0
            mask[nr:, :] = 0

            # creat Nansat object and add bands
            self.resize(width=ice.shape[1])
            nIceType = Nansat(domain=self, logLevel=self.logger.level)
            nIceType.add_band(array=ice, parameters={'name': 'ice'})
            nIceType.add_band(array=mask, parameters={'name': 'mask'})
            nIceType.add_band(array=icemap, parameters={'name': 'icemap'})

            # set date in output nansat
            selftime = self.get_time()[0].strftime('%Y-%m-%d %H:%M:%S.%f')
            nIceType.set_metadata('start_date', selftime)

            # export L2 data into GeoTIFF
            nIceType.export(resultName, driver='GTiff')
            time.sleep(1)
            self.resize()

        # 2. save ice map
        if not os.path.exists(icemapName):
            self.logger.info('Generating %s' % icemapName)
            f = Figure(np.zeros(icemap.shape), cmin=[0], cmax=[1],
                                        mask_array=icemap,
                                        mask_lut={0:[0,0,0],
                                                 1:[100,200,100],
                                                 2:[230,230,230],
                                                 3:[240,240,240],
                                                 4:[255,255,255],
                                                 5:[0,0,150],
                                                 6:[0,0,200],
                                                 7:[0,0,255]},
                                        numOfColor=200)
            f.process()
            f.save(icemapName)
            time.sleep(1)

        self.resize()

        return 0
