from raven import Client

from app.core.celery_app import celery_app
from app.core.config import settings
import requests
from pathlib import Path
from urllib.parse import urlparse, urljoin

client_sentry = Client(settings.SENTRY_DSN)

download_to_local_url = urljoin(settings.SERVER_ADDRESS, settings.API_V1_STR, "/videos/worker")
upload_to_server_url = urljoin(settings.SERVER_ADDRESS, settings.API_V1_STR, "/videos/worker")

ZIP_STORAGE = Path("/app").joinpath(settings.CELERY_ZIP_STORAGE)
VIDEO_STORAGE = Path("/app").joinpath(settings.CELERY_VIDEO_STORAGE)


@celery_app.task(acks_late=True)
def test_celery(word: str) -> str:
    return f"test task return {word}"

@celery_app.task(acks_late=True)
def download_to_local(id:int, file_name:str) -> str:

    zip_file = Path(file_name+"/.zip")
    r = requests.get(download_to_local_url, stream=True)

    with open(str(VIDEO_STORAGE/zip_file), 'wb') as f:
        r.raise_for_status()
        for chunk in r.iter_content(chunk_size=1024):
            f.write(chunk)
    return "complete"


@celery_app.task(acks_late=True)
def make_video(id:int, file_name) -> str:
    # download 
    zip_file = Path(file_name+"/.zip")
    r = requests.get(download_to_local_url, stream=True)

    with open(str(VIDEO_STORAGE/zip_file), 'wb') as f:
        r.raise_for_status()
        for chunk in r.iter_content(chunk_size=1024):
            f.write(chunk)

    # make video


    video_file = Path(file_name+".mp4")
    r = requests.post(urljoin(upload_to_server_url,str(id)))


    return "complete"


@celery_app.task(acks_late=True)
def upload_to_server(id:int, file_name:str) -> str:

    video_file = Path(file_name+".mp4")
    r = requests.post(urljoin(upload_to_server_url,str(id)))
    return "complete"