import re
from flask import jsonify, make_response, request

from src.config import Configuration
from src.lib.files import get_file_relationships, try_set_password
from src.utils.utils import get_query_parameters_dict, parse_int, positive_or_none, step_int
from src.lib.filehaus import get_all_shares_count, get_files_for_share, get_share, get_shares
from src.lib.api import create_not_found_error_response, create_client_error_response
from src.pages.api.v1 import v1api_bp


HASH_REGEX = re.compile(r"[a-f0-9]{64}")


@v1api_bp.get("/search_hash/<file_hash>")
def lookup_file(file_hash: str):
    file_hash = file_hash.lower()
    if not HASH_REGEX.match(file_hash):
        return create_client_error_response("Invalid SHA256 hash")

    file = get_file_relationships(file_hash)

    response = make_response(jsonify(file), 200)
    response.headers["Cache-Control"] = "s-maxage=600"

    return response


@v1api_bp.route("/shares")
def get_shares_data():
    base = request.args.to_dict()
    base.pop("o", None)

    limit = 50
    offset = positive_or_none(step_int(parse_int(request.args.get("o"), 0), limit))
    # query = request.args.get('q')

    shares = None
    total_count = None
    (shares, total_count) = get_share_page(offset, limit)

    props = dict(currentPage="shares", count=total_count, shares=shares, limit=limit)

    response = make_response(
        jsonify(
            props=props,
            base=base,
        ),
        200,
    )
    response.headers["Cache-Control"] = "s-maxage=60"

    return response


def get_share_page(offset: int, limit: int):
    posts = get_shares(offset, limit)
    total_count = get_all_shares_count()

    return posts, total_count


@v1api_bp.get("/share/<share_id>")
def get_share_handler(share_id: str):
    base = request.args.to_dict()
    base.pop("o", None)

    if (not share_id.isdigit()):
        return create_client_error_response("Invalid share ID.")

    share = get_share(int(share_id))

    if share is None:
        return create_not_found_error_response("Share not found.")

    share_files = get_files_for_share(share["id"])

    response = make_response(
        jsonify(share_files=share_files, share=share, base=base),
        200,
    )
    response.headers["Cache-Control"] = "s-maxage=60"

    return response
