#!/usr/bin/python

from datetime import datetime
from pathlib import Path
from glouton.services.observation.observationsService import ObservationsService
from glouton.services.telemetry.telemetryService import TelemetryService
from glouton.services.session.sessionService import SessionService
from glouton.domain.parameters.programCmd import ProgramCmd
from glouton.shared.logger import logger
import argparse
import sys


def glouton():
    print("""                   .-'''-.                     .-'''-.                """)
    print("""          .---.   '   _    \                  '   _    \              """)
    print("""          |   | /   /` '.   \               /   /` '.   \    _..._    """)
    print("""  .--./)  |   |.   |     \  '              .   |     \  '  .'     '.  """)
    print("""  /.''\\   |   ||   '      |  '          .| |   '      |  '.   .-.   . """)
    print("""| |  | |  |   |\    \     / /         .' |_\    \     / / |  '   '  | """)
    print(""" \`-' /   |   | `.   ` ..' /_    _  .'     |`.   ` ..' /  |  |   |  | """)
    print(
        """ /("'`    |   |    '-...-'`| '  / |'--.  .-'   '-...-'`   |  |   |  | """)
    print(""" \ '---.  |   |           .' | .' |   |  |                |  |   |  | """)
    print("""  /'""'.\ |   |           /  | /  |   |  |                |  |   |  | """)
    print(""" ||     ||'---'          |   `'.  |   |  '.'              |  |   |  | """)
    print(""" \'. __//                '   .'|  '/  |   /               |  |   |  | """)
    print("""  `'---'                  `-'  `--'   `'-'                '--'   '--' """)
    print('\tSATNOGS DATA DOWNLOADER')
    print('\t-----------------------\n')


if __name__ == "__main__":
    try:
        glouton()
        parser = argparse.ArgumentParser(description='Execute get request.')
        # Network API parameters :
        parser.add_argument('--norad', '-n', dest='norad_id', required='--last' not in sys.argv,
                            help='the norad satellite id')
        parser.add_argument('--gsid', '-g', dest='ground_station_id',
                            help='the ground station id')
        parser.add_argument('--status', '-t', dest='status',
                            help='the Observation status (good, bad, unknown, failed')
        parser.add_argument('--sdate', '-s', dest='start_date', required='--last' not in sys.argv,
                            help='start date (ex: 2018-01-20T00:51:54)')
        parser.add_argument('--edate', '-e', dest='end_date', required='--last' not in sys.argv,
                            help='end date (ex: 2018-01-21T00:51:54)')
        parser.add_argument('--user', '-u', dest='user_id',
                            help='the user id')
        parser.add_argument('--tuuid', '-i', dest='transmitter_uuid',
                            help='the transmitter uuid')
        parser.add_argument('--tmode', '-m', dest='transmitter_mode',
                            help='the transmitter mode')
        parser.add_argument('--ttype', '-y', dest='transmitter_type',
                            help='the transmitter type')
        parser.add_argument('--wdir', '-w', dest='working_dir', default='.',
                            help='the working directory')
        parser.add_argument('--auto', '-a', dest='auto',
                            help='download new sat data automatically (not implemented yet!)')
        parser.add_argument('--archive', '-p', dest='download_archive', default=False, action="store_true",
                            help='download archive data')
        parser.add_argument('--waterfall', '-f', dest='download_waterfall', default=False, action="store_true",
                            help='download waterfall data')
        parser.add_argument('--demoddata', '-d', dest='download_demoddata', default=False, action="store_true",
                            help='download demod data')
        parser.add_argument('--demod-module', dest='demoddata_modules', default=None,
                            help='list of the modules to use while downloading demoddata(s) separated by a ,')
        parser.add_argument('--demod-end-module', dest='demoddata_end_modules', default=None,
                            help='list of the modules to use after downloading demoddata(s) separated by a ,')
        parser.add_argument('--archive-module', dest='archive_modules', default=None,
                            help='list of the modules to use while downloading archive(s) separated by a ,')
        parser.add_argument('--archive-end-module', dest='archive_end_modules', default=None,
                            help='list of the modules to use after downloading archive(s) separated by a ,')
        parser.add_argument('--waterfall-module', dest='waterfall_modules', default=None,
                            help='list of the modules to use while downloading waterfall(s) separated by a ,')
        parser.add_argument('--waterfall-end-module', dest='waterfall_end_modules', default=None,
                            help='list of the modules to use after downloading waterfall(s) separated by a ,')
        parser.add_argument('--last', dest='last', action='store_true',
                            help='restart a download from the last command line.')
        # DB API parameters :
        parser.add_argument('--db', dest='db', action='store_true', default=False,
                            help='download data from satnogs db api')
        parser.add_argument('--frame-module', dest='frame_modules', default=None, required='--db' in sys.argv,
                            help='list of the modules to use while downloading frame(s) separated by a ,')
        parser.add_argument('--frame-end-module', dest='frame_end_modules', default=None,
                            help='list of the modules to use after downloading frame(s) separated by a ,')
        parser.add_argument('--transmitter', dest='transmitter', default=None,
                            help='transmitter filter')
        parser.add_argument('--app-source', dest='app_source', default=None,
                            help='app source filter')
        parser.add_argument('--observer', dest='observer', default=None,
                            help='observer filter')

        args = parser.parse_args()
        session = SessionService()
        start_date = None
        end_date = None
        if args.last is True:
            cmd = session.load_last_program_parameters()
        else:
            if args.start_date is not None:
                start_date = datetime.strptime(
                    args.start_date, '%Y-%m-%dT%H:%M:%S')

            if args.end_date is not None:
                end_date = datetime.strptime(
                    args.end_date, '%Y-%m-%dT%H:%M:%S')

            archive_modules = None
            archive_end_modules = None
            demoddata_modules = None
            demoddata_end_modules = None
            waterfall_modules = None
            waterfall_end_modules = None
            frame_modules = None
            frame_end_modules = None
            if args.archive_modules is not None:
                archive_modules = args.archive_modules.split(',')
            if args.archive_end_modules is not None:
                archive_end_modules = args.archive_end_modules.split(',')
            if args.demoddata_modules is not None:
                demoddata_modules = args.demoddata_modules.split(',')
            if args.demoddata_end_modules is not None:
                demoddata_end_modules = args.demoddata_end_modules.split(',')
            if args.waterfall_modules is not None:
                waterfall_modules = args.waterfall_modules.split(',')
            if args.waterfall_end_modules is not None:
                waterfall_end_modules = args.waterfall_end_modules.split(',')
            if args.frame_modules is not None:
                frame_modules = args.frame_modules.split(',')
            if args.frame_end_modules is not None:
                frame_end_modules = args.frame_end_modules.split(',')
            cmd = ProgramCmd(args.norad_id,
                             args.ground_station_id,
                             start_date,
                             end_date,
                             args.status,
                             args.working_dir,
                             args.download_archive,
                             args.download_waterfall,
                             args.download_demoddata,
                             archive_modules,
                             archive_end_modules,
                             demoddata_modules,
                             demoddata_end_modules,
                             waterfall_modules,
                             waterfall_end_modules,
                             args.user_id,
                             args.transmitter_uuid,
                             args.transmitter_mode,
                             args.transmitter_type,
                             frame_modules,
                             frame_end_modules,
                             args.observer,
                             args.app_source,
                             args.transmitter)
            session.save_program_parameters(cmd)

        if args.db is False:
            obs = ObservationsService(cmd)
            obs.extract()
        else:
            tlm = TelemetryService(cmd)
            tlm.extract()

        logger.Info("\n\nall jobs are finished\t(   ^ o^)\m/")
        logger.Info("data are stored in " +
                    str(Path(args.working_dir).absolute()))
    except KeyboardInterrupt:
        print("Exit...")
        sys.exit()
    except ValueError as e:
        logger.Error(e)
    except Exception as ex:
        logger.Error(ex)

# -s 2017-05-20T00:51:54 -e 2017-09-20T00:51:54 -n 25338
# -s 2018-01-20T00:51:54 -e 2018-01-21T00:51:54 -n 28654
# -s 2017-09-19T00:51:54 -e 2017-09-20T00:51:54 -n 25338 --waterfall-module TestModule
# -s 2019-04-09T00:51:54 -e 2019-04-13T00:51:54 -n 28654
