#!/usr/bin/env python

# Copyright 2020 KCL-BMEIS - King's College London
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#     http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import argparse

from datetime import datetime, timezone
import os
import sys
import h5py

try:
    import hystore
except ModuleNotFoundError:
    fixed_path = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
    sys.path.append(fixed_path)
    import hystore

from hystore.core import importer
from hystore.covidspecific import postprocess

parser = argparse.ArgumentParser()
parser.add_argument('--version', action='version', version=hystore.__version__)

subparsers = parser.add_subparsers(dest='command')

parser_import = subparsers.add_parser('import')
parser_import.add_argument('-te', '--territories', default=None,
                           help=('The territory/territories to filter the dataset on '
                                 '(runs on all territories if not set)'))
parser_import.add_argument('-s', '--schema', required=True,
                           help='The location and name of the schema file')
parser_import.add_argument('-i', '--inputs', required=True)
parser_import.add_argument('-o', '--output_hdf5',
                           help='The location and name of the output hdf5 file. If this is an existing file, it will'
                                ' be overwritten')
parser_import.add_argument('-ts', '--timestamp', default=str(datetime.now(timezone.utc)),
                           help='Override for the import datetime (the current time is selected otherwise)')

parser_postprocess = subparsers.add_parser('process')
parser_postprocess.add_argument('-i', '--input', required=True, help='The dataset to load')
parser_postprocess.add_argument('-o', '--output', required=True,
                                help='The dataset to write results to. If this is an existing file, it will be'
                                     ' overwritten')
parser_postprocess.add_argument('-d', '--daily', action='store_true',
                                help='If set, generate daily assessments from assessments')

args = parser.parse_args()

if 'dev' in hystore.__version__:
    msg = ("Warning: this is a development version of hystore ({}). "
           "Please use one of the release versions for actual work")
    print(msg.format(hystore.__version__))

# TODO: a proper mechanism to register commands / handlers for commands
if args.command == 'import':
    errors = False
    if not os.path.isfile(args.schema):
        print('-s/--schema argument must be an existing file')
        errors = True
    inputs = args.inputs.split(',')
    tokens = [i.strip() for i in inputs]
    if any(':' not in t for t in tokens):
        raise ValueError("'-i/--inputs': must be composed of a comma-separated list of name:file")
    tokens = {t[0]: t[1] for t in (t.split(':', 1) for t in tokens)}
    print(tokens)
    for tk, tv in tokens.items():
        if not os.path.isfile(tv):
            print("-i/--import_data - {}: '{}' must be an existing file".format(tk, tv))
            errors = True
    # if args.patient_data is not None and not os.path.isfile(args.patient_data):
    #     print('-p/--patient_data argument must be an existing file')
    #     errors = True
    # if args.assessment_data is not None and not os.path.isfile(args.assessment_data):
    #     print('-a/--assessment_data argument must be an existing file')
    #     errors = True
    # if args.test_data is not None and not os.path.isfile(args.test_data):
    #     print('-t/--test_data argument must be an existing file')
    #     errors = True

    if errors:
        exit(-1)

    # files = {}
    # if args.patient_data is not None:
    #     files['patients'] = args.patient_data
    # if args.assessment_data is not None:
    #     files['assessments'] = args.assessment_data
    # if args.test_data is not None:
    #     files['tests'] = args.test_data
    importer.import_with_schema(args.timestamp, args.output_hdf5, args.schema, tokens)
elif args.command == 'process':
    timestamp = str(datetime.now(timezone.utc))

    flags = set()
    if args.daily is True:
        flags.add('daily')

    with h5py.File(args.input, 'r') as ds:
        with h5py.File(args.output, 'w') as ts:
            postprocess.postprocess(ds, ts, timestamp, flags)
