#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: ai ts=4 sts=4 et sw=4
# Alan Viars

import argparse
import functools
import hashlib
import json
import os
import time
import string
import sys
from collections import OrderedDict
import ndjson
import requests
from jdt.ndjson2fhir import ndjson2fhir

if __name__ == "__main__":

    # Parse args
    parser = argparse.ArgumentParser(
        description='Load an NDJSON document into a FHIR server (via HTTP)')
    parser.add_argument(
        dest='input_ndjson_file',
        action='store',
        help='Input the NDJSON file to load here')
    parser.add_argument(
        dest='fhir_base_url',
        action='store',
        help="Enter the FHIR base URL where you want to create new new FHIR resources.")
    parser.add_argument('-t', '--token', dest='oauth2_token', action='store',
                        default=None,
                        help='Pass a given Bearer token in the Authorization header to the FHIR server.')
    parser.add_argument('-u', '--update', dest='update', action='store_true',
                        help='Perfom an HTTP PUT (UPDATE) instead of a POST/CREATE to the the FHIR server.')
    
    parser.add_argument('-o', '--output-fhir-responses', dest='output_http_response', action='store_true',
                        help='Output the HTTP response for each attempted FHIR POST/PUT to the console.')
    args = parser.parse_args()

    result = ndjson2fhir(args.input_ndjson_file, args.fhir_base_url, 
                         args.oauth2_token, args.update,
                         args.output_http_response)

    # output the JSON transaction summary
    print(json.dumps(result, indent=4))
    ndjson2fhir_results_json_file = open("%s-results.json" % (args.input_ndjson_file),'w')
    ndjson2fhir_results_json_file.write(json.dumps(result, indent=4))
    ndjson2fhir_results_json_file.close()