from my_modules.decoratory.header import login_required
from my_modules.functions import get_ip
from my_modules.app.setup import LIMITER
from my_modules.app.logger import logger

from quart import Blueprint, request, session, Response, send_file, render_template, abort, current_app

side_main_bp = Blueprint('side_main', __name__)

@side_main_bp.route('/')
@LIMITER.limit("10 per minute;50 per hour")
async def index():
  if session.get("user") is not None:
    return await render_template("views/webpage/files/upload.htm")
  return await render_template("views/webpage/index.htm")

@side_main_bp.route('/access')
@login_required
async def access_list(user):
  access_data = await current_app.convex.get_all_access(user_id=user['sub'])
  return await render_template("views/webpage/access/list.htm", access_logs=access_data)

@side_main_bp.route('/files')
@login_required
async def files_list(user):
  files_data = await current_app.convex.get_files(user_id=user['sub'])
  return await render_template("views/webpage/files/list.htm", files=files_data)

@side_main_bp.route('/files/<path:file_id>/info')
@login_required
async def file_info(file_id, user):
  files_data = await current_app.convex.get_files(user_id=user['sub'])
  return await render_template("views/webpage/files/info.htm", files=files_data)

@side_main_bp.route('/files/<path:file_id>/edit')
@login_required
async def file_edit(file_id, user):
  files_data = await current_app.convex.get_files(user_id=user['sub'])
  return await render_template("views/webpage/files/edit.htm", files=files_data)

@side_main_bp.route("/-<file_id>")
@LIMITER.limit("10 per minute;500 per hour;")
async def serve_file(file_id: str):
  file_data = await current_app.convex.get_file(file_id=file_id)
  disable_logging = False

  if not file_data:
    abort(404)

  user = session.get('user')
  if user and user['sub'] == file_data['user_id']:
    disable_logging = True

  if file_data.get("expired", None):
    if not disable_logging:
      await current_app.convex.add_file_access(file_id=file_id, ip_address=get_ip(), user_agent=request.user_agent, status="expired")
    return Response("This file has expired.", status=410, headers={
      "Cache-Control": "no-store",
      "X-Content-Type-Options": "nosniff",
    })

  file_name = file_data.get("file_name")
  content_type = file_data.get("content_type") or "application/octet-stream"

  force_download = request.args.get("download") in {"1", "true", "yes"}

  if not file_data.get('db_image_url', None):
    if not disable_logging:
      await current_app.convex.add_file_access(file_id=file_id, ip_address=get_ip(), user_agent=request.user_agent, status="error")
    abort(404)

  if not disable_logging:
    await current_app.convex.add_file_access(file_id=file_id, ip_address=get_ip(), user_agent=request.user_agent, status="ok")

  return await send_file(
    filename_or_io=await current_app.convex.get_from_storage(file_data.get('db_image_url')),
    mimetype=content_type,
    as_attachment=force_download,
    attachment_filename=file_name,
    conditional=True,
    cache_timeout=60,
    last_modified=int(file_data['uploaded_at']) / 1000
  )
