import sys
import json
import argparse
import subprocess

parser = argparse.ArgumentParser()
parser.add_argument("--in", dest="input_video", help="input video", action="store", default="")
parser.add_argument("--jsonout", dest="jsonout", help="input video", action="store", default="")
args = parser.parse_args()

def getCalibrationJSON(path, outpath):
    trackId = 1

    while True:
        print(f"reading {trackId} as {outpath}")
        err = subprocess.call(["mkvextract", args.input_video, "attachments", f"{trackId}:{outpath}"], stderr=None)
        if err:
            # not found.
            return None
        with open(outpath, 'r') as fh:
            cal = None
            try:
                jsonstr = fh.read()
                cal = json.loads(jsonstr)
            except json.decoder.JSONDecodeError:
                print(f"Rejecting non-json attachment {trackId}...")
                continue

            # otherwise we have a json object!
            if 'CalibrationInformation' in cal:
                print("calibration.json found!")
                return True
        trackId = trackId + 1
    return None

getCalibrationJSON(args.input_video, args.jsonout)
