#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Copyright (c) 2014, 2015, 2016 Adam.Dybbroe

# Author(s):

#   Adam.Dybbroe <a000680@c14526.ad.smhi.se>

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

"""Get the PPS cloud mask data for some scenes and do the satellite-synop
co-location. Write data to files. One file for each satellite swath.
"""

import os
from glob import glob
from datetime import datetime, timedelta
import pandas as pd
import numpy as np

from pypps_reader import NwcSafPpsData
from pyresample import spherical_geometry
from pykdtree.kdtree import KDTree
from synop_dwd import get_data

# The window size over which the satellite cloud cover is derived:
ROW_SZ, COL_SZ = (20, 20)
# ROW_SZ, COL_SZ = (6, 6)
# The time it takes for one sensor scan line:
# AVHRR, scans the earth at a rate of 6 scans per second
# GAC AVHRR, scan rate is 2 GAC scans per second
LINE_TIME = {}
LINE_TIME['avhrr_lac'] = timedelta(seconds=1. / 6.)
LINE_TIME['avhrr_gac'] = timedelta(seconds=1. / 2.)
LINE_TIME['viirs'] = timedelta(seconds=86. / (48. * 16))

time_thr = timedelta(seconds=1800)
# time_thr = timedelta(seconds=3600*6)
time_thr_swath = timedelta(seconds=(1800 + 100 * 60))

# ROOTDIR = "/media/Elements/data/pps_v2014_val"
# ROOTDIR = "/local_disk/data/pps_test"
# ROOTDIR = "/nobackup/smhid11/sm_ninha/pps/data_osisaf_noaa"
ROOTDIR = "/nobackup/smhid11/sm_ninha/pps/data_osisaf"
# ROOTDIR = "/run/media/a000680/Elements/data/VIIRS_processed_with_ppsv2014patch_plus"
# ROOTDIR = "/nobackup/smhid11/sm_adam/pps/data_osisaf
# ROOTDIR = "/home/a000680/data/pps_val_v2014"

OVERWRITE = True
SYNOP_DATADIR = "../DataFromDwd"
OUTPUT_DIR = "./data"

INSTRUMENT = {'npp': 'viirs', 'noaa18': 'avhrr', 'noaa19': 'avhrr'}
ANGLE_NAMES = ['SUNZ', 'SATZ', 'SSAZD']
SAT_FIELDS = {}
SAT_FIELDS['viirs'] = ['sunz', 'satz', 'ssazd', 'ciwv', 'tsur', 'm05',
                       'm07', 'm09', 'm10', 'm11', 'm12', 'm14', 'm15', 'm16']
SAT_FIELDS['avhrr'] = ['sunz', 'satz', 'ssazd', 'cwiv', 'tsur', '1',
                       '2', '3a', '3b', 'dummy', '4', '5']

CTYPE_PATTERN = "S_NWC_CT_{satellite:s}_{orbit:5d}_{start_time:%Y%m%dT%H%M%S}{tenthsec_start:1d}Z_{end_time:%Y%m%dT%H%M%S}{tenthsec_end:1d}Z.h5"
FILE_PATTERN = "export/{start_month:%Y%m}/S_NWC_{product:s}_{satellite:s}_{orbit:5d}_{start_date:%Y%m%d}T{start_time:%H%M%S}{tenthsec_start:1d}Z_{end_time:%Y%m%dT%H%M%S}{tenthsec_end:1d}Z.h5"
# FILE_PATTERN = "export/S_NWC_{product:s}_{satellite:s}_{orbit:5d}_{start_date:%Y%m%d}T{start_time:%H%M%S}{tenthsec_start:1d}Z_{end_time:%Y%m%dT%H%M%S}{tenthsec_end:1d}Z.h5"

EPOCH = datetime(1970, 1, 1)

from trollsift import Parser
pps_fparser = Parser(FILE_PATTERN)
ctype_parser = Parser(CTYPE_PATTERN)


class SatellitePointData(object):

    def __init__(self):
        self.lon = 0
        self.lat = 0
        self.id = None
        self.time = None
        self.deltatime = 0
        self.cloudcover = 0
        self.cloudtype = 0
        self.channels = {}
        self.nwp = {}
        self.angles = {}

    def __str__(self):
        retv = ('Lon = ' + str(self.lon) + '\nLat = ' + str(self.lat) +
                '\nName/Id = ' + str(self.id) + '\n' +
                'Time = ' + str(self.time) + '\n' +
                'Time diff = ' + str(self.deltatime) + '\n' +
                'Cloud cover = ' + str(self.cloudcover) + '\n' +
                'Cloudtype = ' + str(self.cloudtype) + '\n')
        for item in [str(key) + ' = ' +
                     str(self.channels[key]) + ' '
                     for key in self.channels.keys()]:
            retv = retv + item
        retv = retv + '\n'
        for item in [str(key) + ' = ' +
                     str(self.angles[key]) + ' '
                     
for key in self.angles.keys()]:
            retv = retv + item

        return retv


def get_satellite_data(point, imagerdata, sunsat_ang
les, nwp_ciwv, nwp_tsur):
    """Get the instrument data and viewing angles"""

    retv = {}
    for idx in range(1, 6):
        if hasattr(sunsat_angles, 'image%.1d' % idx):
            obj = getattr(sunsat_angles, 'image%.1d' % idx)
            info = getattr(obj, 'info')
            for angle_name in ANGLE_NAMES:
                if info['product'] == angle_name:
                    dname = angle_name.lower()
                    value = getattr(obj, 'data')[point[0], point[1]]
                    if value != info['nodata'] or value != info['missingdata']:
                        retv[dname] = value * info['gain'] + info['offset']
                    else:
                        retv[dname] = -999

    if hasattr(nwp_ciwv, 'ciwv'):
        obj = getattr(nwp_ciwv, 'ciwv')
        info = getattr(obj, 'info')
        value = getattr(obj, 'data')[point[0], point[1]]
        dname = 'ciwv'
        if value != info['nodata']:
            retv[dname] = value * info['gain'] + info['intercept']
        else:
            retv[dname] = -999

    if nwp_tsur and hasattr(nwp_tsur, 'tsur'):
        obj = getattr(nwp_tsur, 'tsur')
        info = getattr(obj, 'info')
        value = getattr(obj, 'data')[point[0], point[1]]
        dname = 'tsur'
        if value != info['nodata']:
            retv[dname] = value * info['gain'] + info['intercept']
        else:
            retv[dname] = -999

    for idx in range(1, 22):
        if hasattr(imagerdata, 'image%d' % idx):
            obj = getattr(imagerdata, 'image%.1d' % idx)
            info = getattr(obj, 'info')
            if info['product'] == 'SATCH':
                dname = info['channel'].lower()
                value = getattr(obj, 'data')[point[0], point[1]]
                if value != info['nodata'] or value != info['missingdata']:
                    retv[dname] = value * info['gain'] + info['offset']
                else:
                    retv[dname] = -999

    return retv


def get_cloud_cover(pps_ctype, point, box):
    """Get the cloud cover around the pixel *point* using a box with dimensions
    *box* """

    try:
        ctypedata = pps_ctype.cloudtype.data
    except AttributeError:
        ctypedata = pps_ctype.ct.data

    shape = ctypedata.shape

    center_val = ctypedata[point[0], point[1]]

    y_left, y_right = point[0] - box[0] / 2, point[0] + box[0] / 2
    x_left, x_right = point[1] - box[1] / 2, point[1] + box[1] / 2
    if (x_left < 0 or y_left < 0 or
            x_right >= shape[1] or y_right >= shape[0]):
        return None, center_val

    ctyarr = ctypedata[y_left: y_right,
                       x_left: x_right]
    ncl = np.sum(np.logical_and(np.greater(ctyarr, 4),
                                np.less(ctyarr, 20)))
    ntot = np.sum(np.logical_and(ctyarr != 0, ctyarr != 20))
    if ntot == 0:
        return None, center_val

    return float(ncl) / float(ntot), center_val


def mask_bounds(boundary, nodata=None):
    """Mask out no-data in the boundary lon,lat coordinates"""

    for idx in range(2):
        mask = np.logical_and(boundary[idx].side1 > -0.999,
                              boundary[idx].side1 < -0.998)
        if nodata:
            mask = np.logical_or(
                mask, np.abs(boundary[idx].side1 - nodata) < 0.01)
        boundary[idx].side1 = np.ma.masked_array(
            boundary[idx].side1, mask=mask)

        mask = np.logical_and(boundary[idx].side2 > -0.999,
                              boundary[idx].side2 < -0.998)
        if nodata:
            mask = np.logical_or(
                mask, np.abs(boundary[idx].side2 - nodata) < 0.01)
        boundary[idx].side2 = np.ma.masked_array(
            boundary[idx].side2, mask=mask)

        mask = np.logical_and(boun