import uuid

from keble_helpers import ProgressHandler

from ..config import redis


def test_new():
    handler = ProgressHandler(redis=redis)
    key = str(uuid.uuid4())
    t = handler.new(key=key)
    assert t.progress_report.progress == 0
    assert t.progress_report.success == 0
    assert t.progress_report.pending == 1
    assert t.progress_report.failure == 0

    t.new_subtask()  # subtask1 =
    subtask2 = t.new_subtask()
    subtask3 = t.new_subtask()

    subtask3.success()
    subtask2.failure(error="error")

    report = handler.get(key=key)
    assert report is not None
    assert report.progress == 0.25
    assert report.success == 1
    assert report.failure == 1
    assert report.pending == 2
    assert len(report.errors) == 1
    assert report.errors[0] == "error"
    assert report.progress_key is not None


def test_new_with_model_key():
    handler = ProgressHandler(redis=redis)

    key = str(uuid.uuid4())
    model_key = str(uuid.uuid4())
    root = handler.new(key=key, model_key=model_key)
    t1 = root.new_subtask()
    t2 = root.new_subtask()
    t3 = root.new_subtask()
    t1.success()
    t2.failure()
    t3.success()
    root.success()

    # expect prebuilt to be length of 3
    new_root = handler.new(key=str(uuid.uuid4()), model_key=model_key)
    assert len(new_root.subtasks) == 3

    # now same model key, but we change its length
    t1 = new_root.new_subtask()
    t2 = new_root.new_subtask()
    t1.success()
    t2.failure()
    new_root.success()

    # expect prebuilt to be length of 2

    new_root = handler.new(key=str(uuid.uuid4()), model_key=model_key)
    assert len(new_root.subtasks) == 2
