#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 31 07:27:16 2024
@author: marik
"""
import time
import solara
import asyncio
from solara.lab import task
import logging
logger = logging.getLogger("tasks")
logger.setLevel(logging.INFO)
number_of_runs = 0
@task
async def fetch_data():
    global number_of_runs
    print(f"fetch_data started, is_current is {fetch_data.is_current()}")
    await asyncio.sleep(2)
    print(f"fetch_data stopped sleeping, is_current is {fetch_data.is_current()}")
    if not fetch_data.is_current():
        print("Trying to cancel")
        fetch_data.cancel()
        return
    number_of_runs = number_of_runs + 1
    print(f"fetch_data finished")
    return f"The answer is 42, # of runs is {number_of_runs}"
@solara.component
def Page():
    with solara.Card("Cancel task demo"):
        solara.Button("Fetch data", on_click=fetch_data)
        solara.ProgressLinear(fetch_data.pending)
        if fetch_data.finished:
            solara.Text(fetch_data.value)
        elif fetch_data.not_called:
            solara.Text("Click the button to fetch data")
        # Optional state check
        elif fetch_data.cancelled:
            solara.Text("Cancelled the fetch")
        elif fetch_data.error:
            solara.Error(str(fetch_data.exception))