import sys, argparse, datetime


# return the fixed interval and polynomial arrays as strings
def intvandpolys(args):
    intvsize = 1.0/args.groupsize
    intvstr = "["
    polystr = "["
    for j in range(args.groupsize):
        if j == 0:
            a = j*intvsize
        else:
            a = j*intvsize + 0.001
        b = (j+1)*intvsize
        intvstr += f'[{a:5.3},{b:5.3}]'
        polystr += f'[0.0, 0.0, 0.0, 0.0] '
        if j < args.groupsize - 1:
            intvstr += ', '
            polystr += ', '

    intvstr += ']'
    polystr += ']'
    return intvstr, polystr


# generate the json calibration file
def nullcalib(args):
    now=datetime.datetime.now()


    intvstr, polystr = intvandpolys(args)

    groupstr = ''
    for i in range(args.groups):
        groupstr += '      {\n'
        groupstr += '        "groupindex" : {},\n'.format(i)
        groupstr += '        "intervals" : {},\n'.format(intvstr)
        groupstr += '        "polynomials" : {}\n'.format(polystr)

        if i < args.groups -1:
            groupstr += '      },\n'
        else:
            groupstr += '      }'

    jsonstr = [
     '{' ,
     '  "Calibration" : {',
     '    "version" : 0,',
     '    "date" : "{}", '.format(now.isoformat()),
     '    "info" : "generated by nullcalib.py", ',
     '',
     '    "instrument" : "{}",'.format(args.name),
     '    "groups" : {},'.format(args.groups),
     '    "groupsize" : {},'.format(args.groupsize),
     '',
     '    "Parameters" : [',
     '{}'.format(groupstr),
     '    ]',
     '  }',
     '}'
    ]
    print("\n".join(jsonstr))


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument("--name", help = "instrument name", type = str)
    parser.add_argument("--groups", help = "number of groups", type = int)
    parser.add_argument("--groupsize", help = "group size (# units per groups)", type = int)
    args = parser.parse_args()

    nullcalib(args)

    # Examples based omn ICDs
    #  --name loki --groups 896 --groupsize 7
    #  --name bifrost --groups 45  --groupsize 3
    #  --name miracles --groups 48  --groupsize 2
