import json

from rauc import parse_rauc_slots, should_download_bundle, get_target_slot


def parse(rauc_output_file):
    with open(rauc_output_file) as file:
        status = json.load(file)
        return parse_rauc_slots(status)


def test_rauc_slots_1():
    slots = parse("data/rauc_status_output_1.json")
    assert len(slots) == 2

    assert not should_download_bundle("2020.04.07", slots)
    assert not should_download_bundle("2020.04.08", slots)
    assert should_download_bundle("2020.04.10", slots)

    target_slot = get_target_slot("2020.04.07", slots)
    assert target_slot and target_slot.slot_name == "rootfs.1"

    target_slot = get_target_slot("2020.04.08", slots)
    assert target_slot and target_slot.slot_name == "rootfs.0"


def test_rauc_slots_2():
    slots = parse("data/rauc_status_output_2.json")
    assert len(slots) == 2

    assert not should_download_bundle("2020.04.07", slots)
    assert not should_download_bundle("2020.04.08", slots)
    assert should_download_bundle("2020.04.10", slots)

    target_slot = get_target_slot("2020.04.07", slots)
    assert target_slot and target_slot.slot_name == "rootfs.1"

    target_slot = get_target_slot("2020.04.08", slots)
    assert target_slot and target_slot.slot_name == "rootfs.0"


def tests_rauc_slots_3():
    slots = parse("data/rauc_status_output_3.json")
    assert len(slots) == 2

    assert not should_download_bundle("2020.04.07", slots)
    assert should_download_bundle("2020.04.08", slots)
    assert should_download_bundle("2020.04.10", slots)

    target_slot = get_target_slot("2020.04.07", slots)
    assert target_slot and target_slot.slot_name == "rootfs.1"


def tests_rauc_slots_4():
    slots = parse("data/rauc_status_output_4.json")
    assert len(slots) == 2

    assert not should_download_bundle("2020.04.07", slots)
    assert not should_download_bundle("2020.04.08", slots)
    assert should_download_bundle("2020.04.10", slots)

    target_slot = get_target_slot("2020.04.07", slots)
    assert target_slot and target_slot.slot_name == "rootfs.1"

    # slot rootfs0 is marked bad, so do not switch to it
    assert not get_target_slot("2020.04.08", slots)
