from flask import Blueprint, abort, flash, g, redirect, request, send_file, url_for

from .. import check_branch, login_required, write_required
from ..attachments import RECORDS, listing, path, record, remove, save
from ..db import commit, get_db, q
from ..i18n import t
from ..ledger import AccountingError, audit
from .common import user_id

bp = Blueprint("attachments", __name__, url_prefix="/attachments")


def target(model, rid):
    if model not in RECORDS:
        abort(404)
    rec = record(model, rid)
    if not rec:
        abort(404)
    check_branch(rec["branch_id"])
    return rec


def back(model, rid):
    _, endpoint, arg = RECORDS[model]
    return redirect(url_for(endpoint, **{arg: rid}) + "#attachments")


def get_attachment(aid):
    att = q("SELECT * FROM attachments WHERE id = ?", (aid,), one=True)
    if not att:
        abort(404)
    target(att["model"], att["record_id"])
    return att


@bp.route("/<model>/<int:rid>", methods=["POST"])
@write_required
def upload(model, rid):
    target(model, rid)
    files = [f for f in request.files.getlist("files") if f and f.filename]
    if not files:
        flash(t("Choose a file to upload."), "error")
        return back(model, rid)
    try:
        for f in files:
            aid = save(model, rid, f, user_id())
            audit(user_id(), "attach", model, rid, f.filename)
        commit()
        flash(f"{len(files)} {t('file attached.') if len(files) == 1 else t('files attached.')}", "success")
    except AccountingError as e:
        get_db().rollback()
        flash(str(e), "error")
    return back(model, rid)


@bp.route("/<int:aid>/<path:name>")
@login_required
def view(aid, name):
    att = get_attachment(aid)
    try:
        full = path(att)
    except FileNotFoundError:
        abort(404)
    inline = att["content_type"] != "application/octet-stream" and not request.args.get("download")
    resp = send_file(full, mimetype=att["content_type"], as_attachment=not inline, download_name=att["filename"])
    resp.headers["X-Content-Type-Options"] = "nosniff"
    if att["content_type"] != "application/pdf":  # the browser's PDF viewer does not run in a sandbox
        resp.headers["Content-Security-Policy"] = "default-src 'none'; img-src 'self'; style-src 'unsafe-inline'; sandbox"
    return resp


@bp.route("/<int:aid>/delete", methods=["POST"])
@write_required
def delete(aid):
    att = get_attachment(aid)
    if att["uploaded_by"] != g.user["id"] and g.user["role"] != "admin":
        flash(t("Only the person who uploaded a file, or an administrator, can remove it."), "error")
        return back(att["model"], att["record_id"])
    remove(att)
    audit(user_id(), "remove attachment", att["model"], att["record_id"], att["filename"])
    commit()
    flash(t("Removed."), "success")
    return back(att["model"], att["record_id"])


@bp.route("/<model>/<int:rid>/note", methods=["POST"])
@write_required
def note(model, rid):
    """Log an internal note on a document (Odoo's chatter)."""
    target(model, rid)
    body = (request.form.get("body") or "").strip()
    if body:
        from ..ledger import now
        from ..db import x
        x("INSERT INTO doc_notes (model, record_id, user_id, ts, body) VALUES (?,?,?,?,?)",
          (model, rid, user_id(), now(), body[:4000]))
        commit()
    _, endpoint, arg = RECORDS[model]
    return redirect(url_for(endpoint, **{arg: rid}) + "#chatter")
