from fastapi import APIRouter, Form, Depends, HTTPException, File, UploadFile
from typing import List,Optional,Union
from fastapi.responses import FileResponse
from random import randint
from fastapi.security import OAuth2PasswordRequestForm
from app.models.models import Tgc_pic,Tgc_report
from app.api import deps
from sqlalchemy.orm import Session
from typing import Any, Dict
import secrets
from fastapi_login.exceptions import InvalidCredentialsException
from fastapi_login import LoginManager
from datetime import timedelta,datetime
from jose import jwt
from emails.template import JinjaTemplate
from tortoise.queryset import Q
from fastapi.responses import HTMLResponse

tgc = APIRouter()

IMAGEDIR = "/var/www/ntcri/assets/tgc_files/"
IMAGEDIR_short = "assets/tgc_files/"


@tgc.post("/upload_tgc_pic")
async def create_upload_files(files:Optional[List[UploadFile]] = File(None)):
    files_url = []
    if files :
        for file in files:
            contents = await file.read()

            #save the file
            with open(f"{IMAGEDIR}{file.filename}", "wb") as f:
                f.write(contents)
                files_url.append(f"{IMAGEDIR_short}{file.filename}")       

    return files_url

@tgc.get("/get_tgc_report")
async def get_tgc_report(
    id : Optional[int] = None,
    keyword : Optional[str] = None,
    page_num : Optional[int] = None,
    page_amount : Optional[int] = None
):
    try:
        report_list = Tgc_report.all()

        if id :
            report_list = report_list.filter(id = id).all()

        if keyword:
            for word in keyword.split(","):
                report_list = report_list.filter(title__icontains = word).all()


        count = await report_list.all().count()

        if page_num and page_amount:
            report_list = report_list.offset((page_num-1)*page_amount).limit(page_amount)

        report_list = await report_list.all().order_by("-create_time")

        result = []

        for report_obj in report_list:
            try :
                result.append(report_obj.show_data())
            except Exception as e:
                result.append({"msg": str(e)})

        return {"msg": "success", "code": 200, "total_num":count,"tgc_report": result }
    except Exception as e:
        return {"msg": str(e), "code": 500}
    
@tgc.post("/input_tgc_report")
async def input_tgc_report(
    title : str = Form(default=''),
    create_time : str = Form(default=datetime.now()),
    url : str = Form(default='')
):
    try:
        new_report = await Tgc_report.create(
            title = title,
            create_time = create_time,
            url = url
        )

        return {"msg": "success", "code": 200, "new_report": new_report.id}
    except Exception as e:
        return {"msg": str(e), "code": 500}
    
@tgc.get("/get_tgc_img")
async def get_tgc_img(
    id : Optional[int] = None,
    page_num : Optional[int] = None,
    page_amount : Optional[int] = None
):
    try:
        tgc_pic_list = Tgc_pic.all()

        Q_word=Q()
        
        if id :
            Q_word = Q(id=id)

        tgc_pic_list = tgc_pic_list.filter(Q_word)  

        count = await tgc_pic_list.all().count()

        if page_num and page_amount:
            tgc_pic_list = tgc_pic_list.offset((page_num-1)*page_amount).limit(page_amount)

        tgc_pic_list= await tgc_pic_list.all()
        result = []

        for obj in tgc_pic_list:
            result.append(obj.show_data())

        return {"msg": "success", "code": 200, "total_num":count,"tgc_pic": result }
    except Exception as e:
        return {"msg": str(e), "code": 500}