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

import argparse
import json
from collections import OrderedDict
from jdt.fhirbundledownsize import fhirbundledownsize

if __name__ == "__main__":

    parser = argparse.ArgumentParser(
        description='Load in FHIR Bunlde and save multiple FHIR Bundles.')
    parser.add_argument(
        dest='bundle_file',
        action='store',
        help='Input the FHIR Bundle.')
    parser.add_argument(
        dest='output_size',
        action='store',
        default="500",
        help="Enter the integer of the maximum number of entries per bundle.")
    args = parser.parse_args()

    in_fh = open(args.bundle_file, 'r')
    bundle_object = json.loads(in_fh.read(), object_pairs_hook=OrderedDict)
    print("The number of entries in the source file is %s" % (len(bundle_object['entry'])))
    result_list = fhirbundledownsize(bundle_object, args.output_size)
    i = 1
    for r in result_list:
        output_file = "%s_%s" % (args.bundle_file, i)
        out_fh = open(output_file, 'w')
        json.dump(r, out_fh)
        out_fh.close()
        print("%s file created." % (output_file))
        i += 1

    # output the JSON transaction summary
    print("%s FHIR Bundles created." % len(result_list))
