from typing import Any, List, Optional
import subprocess
from fastapi import UploadFile, File, Form
from fastapi.responses import FileResponse
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session

import app.crud as crud
import app.models as models
import app.schemas as schemas 
from app.api import deps

from app.core.celery_app import celery_app
from app.core.config import settings
from pathlib import Path

from app.core.celery_app import celery_app

BACKEND_ZIP_STORAGE = Path("/app").joinpath(settings.BACKEND_ZIP_STORAGE)
LOCAL_ZIP_STORAGE = Path("/").joinpath(settings.LOCAL_ZIP_STORAGE)


router = APIRouter()

@router.get("/", response_model=List[schemas.Video])
def get_video_list(
    db: Session = Depends(deps.get_db),
    skip: int = 0,
    limit: int = 100,
    current_user: models.User = Depends(deps.get_current_active_user),
) -> Any:
    """
    Retrieve items.
    """
    if crud.user.is_superuser(current_user):
        videos = crud.video.get_multi(db, skip=skip, limit=limit)
    else:
        videos = crud.video.get_multi_by_owner(
            db=db, owner_id=current_user.id, skip=skip, limit=limit
        )
    return videos

@router.post("/", response_model=schemas.Video)
def upload_plot(
    *,
    db: Session = Depends(deps.get_db),
    title: str=Form(...), 
    anchor_id: int=Form(...),
    lang_id: int=Form(...),
    upload_file: UploadFile=File(),
    current_user: models.User = Depends(deps.get_current_active_user),
) -> Any:
    """
    Create new video.
    """
    print(title)
    print(upload_file.filename)
    file_name = crud.video.generate_file_name(db=db, n=20)
    video_create = schemas.VideoCreate(title=title, progress_state="waiting", stored_file_name=file_name)
    video = crud.video.create_with_owner(db=db, obj_in=video_create, owner_id=current_user.id)

    try:
        with open(str(Path(BACKEND_ZIP_STORAGE).joinpath(video.stored_file_name+".zip")), 'wb') as f:
            while contents := upload_file.file.read(1024 * 1024):
                f.write(contents)
    except Exception as e:
        print(e, type(e))
        return {"error": str(e)}
    finally:
        upload_file.file.close()
    zip_filename = video.stored_file_name+".zip"
    print(str(BACKEND_ZIP_STORAGE/zip_filename))
    r = subprocess.run(["sshpass", "-p", "choozmo9", 
                    "scp", "-P", "5722", "-o", "StrictHostKeyChecking=no", f"{str(BACKEND_ZIP_STORAGE/zip_filename)}", f"root@172.104.93.163:{str(LOCAL_ZIP_STORAGE/zip_filename)}"])
    print(r.returncode)
    celery_app.send_task("app.worker.make_video", args=[video.id, video.stored_file_name, current_user.id])
    return video

@router.get("/{id}")
def download_video(
    *,
    db: Session = Depends(deps.get_db),
    id: int,
    current_user: models.User = Depends(deps.get_current_active_user),
) -> Any:
    
    return {"message":"address"}

