from __future__ import annotations
import json
from flask_restful import Resource
from flask import current_app as app, jsonify, request
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from modules.Archive.database import Database

class Archive_GetPosts(Resource):
    def get(self):
        db : Database = app.databases["Archive"]
        try:
            count = int(request.args["count"]) if "count" in request.args else 20
            page = int(request.args["page"]) if "page" in request.args else 1
            artist = request.args["artist"] if "artist" in request.args else None
            last_id = int(request.args["last_id"]) if "last_id" in request.args else -1
        except:
            response = app.response_class(status=400)
            response.headers.add("Access-Control-Allow-Origin", "*")
            return response   

        actions = []
        if "undecided" in request.args:
            actions.append(0)
        if "approved" in request.args:
            actions.append(1)
        if "denied" in request.args:
            actions.append(2)
        if "hidden" in request.args:
            actions.append(3)
        if actions == []:
            actions = [0,1,2,3]

        ratings = []
        if "SFW" in request.args:
            ratings.append("SFW")
        if "NSFW" in request.args:
            ratings.append("NSFW")
        if "NSFL" in request.args:
            ratings.append("NSFL")
        if ratings == []:
            ratings = ["SFW", "NSFW"]

        if "random" in request.args:
            order = "RAND"
        elif "ascending" in request.args:
            order = "ASC"
        else:
            order = "DESC"

        real_page = page-1
        offset = real_page * count

        result = db.get_posts(count, artist, actions_taken=actions, last_id= -1, offset= offset, include_ratings= ratings, order=order)

        if result is None:
            response = app.response_class(status=400)
        else:
            response = app.response_class(
                response=json.dumps(result, ensure_ascii=False, indent=1),
                status=200,
                mimetype='application/json'
            )

        response.headers.add("Access-Control-Allow-Origin", "*")
        return response