#!/usr/bin/env python3

# Copyright (C) 2018-2020 Simon Spöhel
#
# 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/>.

import logging
import pickle
import os
import datetime as dt

from sentinelsat import SentinelAPI

def _get_tileid(metadata):
        """Returns the tileid of a product.
        Unfortunately only the level-1c product has the tileid in the
        metadata. For the level-1a product extract the tileid from the
        filename."""

        try:
            return(metadata['tileid'])
        except KeyError:
            return(metadata['filename'].split('_')[5][1:])


def download(username, password, base_dest, downloaded_files, index, row, debug_save=False):

    logger = logging.getLogger('sentinel.download')

    sentinel_api = SentinelAPI(username, password)

    tile_uuid = row.uuid
    tile_id = _get_tileid(row)
    tile_date = row['beginposition'].to_pydatetime().date()
    tile_title = row.title
    tile_footprint = row.footprint
    tile_product_type = row.producttype


    if tile_date >= dt.date(2016,12,6):
        logging.debug('handling dates newer than 2016-12-06.')
        destpath = '%s/%s/%s/%s/%s' %(base_dest,
                                      tile_product_type,
                                      downloaded_files,
                                      tile_id,
                                      tile_date.year)
    elif tile_date < dt.date(2016,12,6):
        logging.debug('handling dates older than 2016-12-06.')
        destpath = '%s/%s/%s/%s-%s' %(base_dest,
                                      tile_product_type,
                                      downloaded_files,
                                      tile_date.year,
                                      tile_date.month)
    else:
        loggin.error('Cannot hanlde tile_date is "%s".' %tile_date)
        sys.exit(1)

    if os.path.isfile( '%s/%s.zip' %(destpath, tile_title) ):
        logging.debug('%s/%s.zip already exists' %(destpath, tile_title) )
        return

    os.makedirs(destpath, exist_ok=True)

    result = sentinel_api.download(tile_uuid, destpath)

    if debug_save == True:
        with open('result.pickle', 'wb') as f:
            pickle.dump(result, f)
            f.truncate()

    with open('%s/md5sums.txt' %destpath, 'a') as outfile:
        outfile.write( '%s %s.zip\n' %(result['md5'], tile_title) )

    with open('%s/footprints.txt' %destpath, 'a') as outfile:
        outfile.write( '%s %s\n' %(tile_title, tile_footprint) )

    return(result)
