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

import time

from netCDF4 import Dataset
import numpy as np

from . import config as cfg


def init_ncfile(filename, instrument, times, lon_center, lat_center, lon_corners,
        lat_corners, sza, orbit_data=None):
    """\
    Write satellite orbit to file.

    If orbit_data is None lon/lat centers and corners need to be provided.
    Arrays in orbit_data need to have shape (nobs, nrow, (ncorner)).
    """
    nobs, nrows, ncorners = lon_corners.shape

    data_origin = ', '.join([
        'Tracer fields from COSMO-GHG simulations',
        'Orbits from SRON orbit simulator',
        'MODIS white-sky albedo (MCD43A3.006)'
    ])

    with Dataset(filename, 'w', format='NETCDF4') as nc:

        # global attributes (add input data)
        nc.setncatts({
            'DESCRIPTION':  'Synthetic Level-2 data for %s' % instrument,
            'DATAORIGIN':   data_origin,

            'CREATOR':      'Gerrit Kuhlmann',
            'EMAIL':        'gerrit.kuhlmann@empa.ch',
            'AFFILIATION':  'Empa Duebendorf, Switzerland',
            'VERSION':      '0.1',
            'DATE CREATED': time.ctime(time.time()),
            'STUDY':        'ESA project - Smartcarb',
        })

        if orbit_data is not None:
            nc.createVariable('input', 'c').setncatts({
                # satellite
                'time_for_one_revolution_in_hours': orbit_data.trev * 24.0,
                'satellite_height_in_km': orbit_data.altitude - cfg.r_earth,
                'local_solar_time_at_the_northward_equator_pass_in_hours': orbit_data.t_node,
                'orbital_inclination_angle_in_degrees': np.rad2deg(orbit_data.inclination),

                # revolution
                'date': '%04d-%02d-%02d' % tuple(orbit_data.date),
                'longitude_at_daytime_equator_pass_in_degrees': np.rad2deg(orbit_data.longitude_eq),

                # scanlines
                'orbit_phase_at_start_of_scanning': orbit_data.phase_start,
                'orbit_phase_at_end_of_scanning': orbit_data.phase_end,
                'time_per_scan_in_seconds': orbit_data.tsamp,

                # swath
                'number_of_detector_rows': orbit_data.nrow,
                'polynomial_parameters_for_alpha': ', '.join(str(v) for v in orbit_data.polyterms_alpha),
                'polynomial_parameters_for_beta': ', '.join(str(v) for v in orbit_data.polyterms_beta),
            })

        # create dimensions
        nobs = nc.createDimension('nobs', nobs)
        nrows = nc.createDimension('nrows', nrows)
        ncorner = nc.createDimension('ncorners', ncorners)

        # create variables
        nc_times = nc.createVariable('time', 'f4', ('nobs','nrows'))
        nc_lat = nc.createVariable('latitude', 'f4', ('nobs', 'nrows'))
        nc_lon = nc.createVariable('longitude', 'f4', ('nobs', 'nrows'))
        nc_lat_corner = nc.createVariable('latitude_corners', 'f4', ('nobs', 'nrows', 'ncorners'))
        nc_lon_corner = nc.createVariable('longitude_corners', 'f4', ('nobs', 'nrows', 'ncorners'))
        nc_sza = nc.createVariable('solar_zenith_angle', 'f4', ('nobs', 'nrows'))

        # fill variables
        nc_times[:,:] = times
        nc_lat[:,:] = lat_center
        nc_lon[:,:] = lon_center
        nc_lat_corner[:,:,:] = lat_corners
        nc_lon_corner[:,:,:] = lon_corners
        nc_sza[:,:] = sza

        # Assign an attribute to the dataset
        nc_times.standard_name = "time_of_measurement"
        nc_times.long_name = "time of measurement since 2015-01-01 00:00:00"
        nc_times.units = "seconds since 2015-01-01 00:00:00"

        nc_lat.standard_name = "latitude"
        nc_lat.long_name = "pixel center latitude"
        nc_lat.units = "degrees north"

        nc_lon.standard_name = "longitude"
        nc_lon.long_name = "pixel center longitude"
        nc_lon.units = "degrees east"

        nc_lat_corner.standard_name = "latitude"
        nc_lat_corner.long_name = "pixel corners latitude"
        nc_lat_corner.units = "degrees north"

        nc_lon_corner.standard_name = "longitude"
        nc_lon_corner.long_name = "pixel corners longitude"
        nc_lon_corner.units = "degrees east"

        nc_sza.standard_name = "solar_zenith_angle"
        nc_sza.long_name = "solar zenith angle"
        nc_sza.units = "degree"



def add_variable(filename, var_name, values, attrs=None):
    """\
    Add variable with attributes to netCDF file.
    """
    with Dataset(filename, 'a') as nc_file:
        if attrs is None:
            attrs = {}

        var = nc_file.createVariable(var_name, 'f4', ('nobs', 'nrows'), zlib=True)
        var.setncatts(attrs)

        if var.shape != values.shape:
            raise ValueError('shapes of value array do not match dimensions')

        var[:] = values






