import os
import time
import re

import numpy as np

from nansat import *


class Sentinel1Image(Nansat):
    '''
    Read parameters from Sentinel1 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='s1a_l1', 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',       "'sentinel1'")
        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.7, 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.7, 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
