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

from datetime import datetime, timedelta
import sys

import numpy as np

import smartcarb as sc



def main(time, origin, area, species='XCO2'):

    if origin == 'Berlin':
        tracer = '%s_BV' % species
    else:
        tracer = '%s_JV' % species

    slice_ = sc.io.get_slice(origin, area=area)

    # read signal and background
    filename = sc.io.create_filename(time, input_files='2D')

    if species == 'XCO2':
        signal, bg, bio = sc.io.read_signal_and_background(
            filename, tracer, time=time, correct_berlin=True, slice_=slice_,
            add_biosphere=True)

        bio = sc.misc.spatial_binning(bio, n=2)
    else:
        signal, bg = sc.io.read_signal_and_background(filename, tracer, time=time,
                correct_berlin=True, slice_=slice_)

    # spatial binning to satellite resolution
    signal = sc.misc.spatial_binning(signal, n=2)
    bg = sc.misc.spatial_binning(bg, n=2)

    if species == 'XCO2':
        return (
            bg.mean(), bg.std(), (bg+signal).mean(), (bg+signal).std(),
            bio.mean(), bio.std()
        )
    else:
        return (
            bg.mean(), bg.std(), (bg+signal).mean(), (bg+signal).std(),
            np.nan, np.nan
        )



if __name__ == '__main__':
    origin = sys.argv[1]    #'Berlin'
    area = int(sys.argv[2]) # 100 # grid cells (i.e. 110 km)
    species = sys.argv[3]

    start = datetime(2015,1,1)
    end = datetime(2015,12,25,23)

    out_filename = 'data/ts_%s_background_%s_%d.dat' % (species, origin, area)

    with open(out_filename, 'w') as out:
        out.write('UTC\tmean_bg\tstd_bg\tmean_tot\tstd_tot\tmean_bio\tstd_bio\n')

        for time in sc.misc.iter_times(start, end):
            print(time)
            out.write('%s\t' % str(time))
            out.write('\t'.join('%e' % v for v in main(time, origin, area, species)))
            out.write('\n')


