import os
import json
import shutil


config = {
    "cameras": {
        "K1": {
            "from": 2101,
            "to": 2370
        },
        "K2": {
            "from": 2223,
            "to": 2504
        },
    },
    "indir": os.path.normpath(os.path.join(os.path.dirname(os.path.realpath(__file__)), "..", "..", "antarstick-data", "Keller Stream", "2011")),
    "outdir": os.path.normpath(os.path.join(os.path.dirname(os.path.realpath(__file__)), "..", "..", "antarstick-data", "Keller Stream DEMO", "2018")),
}


if os.path.isdir(config["outdir"]):
    shutil.rmtree(config["outdir"])


with open(os.path.join(config["indir"], "classifier_results.json"), "r") as f:
    classifier_results = json.load(f)


def image_name_to_index(name: str) -> int:
    return int(name[4:name.index(".")])


def image_index_to_name(idx: int) -> str:
    return "IMAG" + format(idx, "04d") + ".JPG"


for cam in config["cameras"]:
    os.makedirs(os.path.join(config["outdir"], "camera_images", cam), exist_ok=True)
    for i in range(config["cameras"][cam]["from"], config["cameras"][cam]["to"] + 1):
        shutil.copyfile(os.path.join(config["indir"], "camera_images", cam, image_index_to_name(i)),
                        os.path.join(config["outdir"], "camera_images", cam, image_index_to_name(i)))


for data in classifier_results["data"]:
    if data["id"] in config["cameras"]:
        keys = [x for x in data.keys()]
        cam = data["id"]
        for key in keys:
            if key == "id":
                continue
            image_idx = image_name_to_index(key)
            if image_idx < config["cameras"][cam]["from"] or config["cameras"][cam]["to"] < image_idx:
                del data[key]
            else:
                recip_data = data[key]["reciprocalImageName"]
                for rcam, rimg in recip_data.items():
                    if rcam not in config["cameras"]:
                        continue
                    ridx = image_name_to_index(rimg)
                    if ridx < config["cameras"][rcam]["from"] or config["cameras"][rcam]["to"] < ridx:
                        recip_data[rcam] = image_index_to_name(config["cameras"][rcam]["from"])


for cam in config["cameras"]:
    for cam_data in classifier_results["data"]:
        if cam != cam_data["id"]:
            continue
        for image_name, image_info in cam_data.items():
            if image_name == "id":
                continue


with open(os.path.join(config["outdir"], "classifier_results.json"), "w") as f:
    json.dump(classifier_results, f, indent=2)


