from time import sleep
from django.core.mail import send_mail
from django.http import HttpResponse
from django.shortcuts import get_object_or_404
from celery import shared_task
from atlas.models import Case
from generic.models import CimarCase
from rad.settings import REMOTE_URL, CIMAR_USERNAME, CIMAR_PASSWORD
from helpers.cimar import CimarAPI, NotFoundError
from pydicom.uid import generate_uid

@shared_task()
def push_case_to_cimar_task(case_id):
    """Sends an email when the feedback form has been submitted."""
    case = get_object_or_404(Case, pk=case_id)

    api = CimarAPI()
    api.login(username=CIMAR_USERNAME, password=CIMAR_PASSWORD)

    # We use the same study_uid for all images in a case
    study_uid = generate_uid()

    for series in case.get_series():
        print(f"Upload series: {series}")
        for image in series.images.filter(removed=False):
            data = api.upload_dicom(image.image.path, study_uid=study_uid)

    
    retries = 5
    delay = 20
    for attempt in range(retries):
        print("attempt 1")
        try:
            cimar_uuid = api.get_study_by_study_uid(data["study_uid"])["uuid"]
            break
        except NotFoundError:
            if attempt < retries - 1:
                sleep(delay)
                delay *= 2
            else:
                cimar_uuid = api.get_study_by_study_uid(data["study_uid"])["uuid"]


    case.cimar_uuid = cimar_uuid

    case.save()

    cimar_case, created = CimarCase.objects.get_or_create(uuid=cimar_uuid)

    cimar_case.refresh_study()

    return 10