"""Foreign-currency revaluation of open invoices and bills at a month end."""
from flask import Blueprint, abort, flash, redirect, render_template, request, url_for

from .. import check_branch, context_branch_ids, login_required, write_required
from ..db import commit, get_db, placeholders, q
from ..fx import cancel_revaluation, open_items, post_revaluation
from ..i18n import t
from ..ledger import AccountingError
from .closing import last_month_end
from .common import branch_map, default_branch, user_id

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


@bp.route("/")
@login_required
def index():
    ids = context_branch_ids()
    d = request.args.get("date") or last_month_end()
    bid = request.args.get("branch", type=int) or default_branch()
    items, branch = (open_items(check_branch(bid), d) if bid else ([], None))
    done = q(f"SELECT r.*, (SELECT COALESCE(SUM(diff), 0) FROM fx_revaluation_lines WHERE reval_id = r.id) AS diff, "
             f"(SELECT COUNT(*) FROM fx_revaluation_lines WHERE reval_id = r.id) AS n FROM fx_revaluations r "
             f"WHERE r.branch_id IN ({placeholders(ids)}) ORDER BY r.date DESC, r.id DESC", list(ids)) if ids else []
    already = bool(bid and q("SELECT 1 FROM fx_revaluations WHERE branch_id = ? AND date = ?", (bid, d), one=True))
    return render_template("fx/index.html", items=items, branch=branch, d=d, bid=bid, branches=branch_map(), done=done,
                           already=already, total=sum(it["diff"] for it in items))


@bp.route("/post", methods=["POST"])
@write_required
def post():
    bid, d = check_branch(request.form["branch_id"]), request.form["date"]
    try:
        post_revaluation(bid, d, user_id())
        commit()
        flash(t("Revaluation posted; it reverses on the next day."), "success")
    except AccountingError as e:
        get_db().rollback()
        flash(str(e), "error")
    return redirect(url_for("fx.index", branch=bid, date=d))


@bp.route("/<int:rid>")
@login_required
def view(rid):
    r = q("SELECT * FROM fx_revaluations WHERE id = ?", (rid,), one=True)
    if not r:
        abort(404)
    check_branch(r["branch_id"])
    lines = q("SELECT l.*, i.number, i.kind, i.date AS inv_date, i.rate AS book_rate, p.name_en, p.name_ar "
              "FROM fx_revaluation_lines l JOIN invoices i ON i.id = l.invoice_id JOIN partners p ON p.id = i.partner_id "
              "WHERE l.reval_id = ? ORDER BY l.currency, i.date", (rid,))
    branch = q("SELECT * FROM branches WHERE id = ?", (r["branch_id"],), one=True)
    if request.args.get("export"):
        from .. import currency_decimals
        from ..exports import Report, respond
        from ..i18n import nm
        rep = Report("Currency Revaluation", [f"{t('Revaluation date')} {r['date']}", f"{branch['code']} {nm(branch)}",
                                              f"{t('Amounts in')} {branch['currency']}"],
                     currency_decimals(branch["currency"]), landscape=True, signatures=True)
        rep.subtitle = r["number"]
        rep.column(t("Document"), width=1.3).column(t("Partner"), width=2).column(t("Currency"), width=0.6) \
            .column(t("Open amount"), "num").column(t("Booked rate"), "qty", 0.8).column(t("Rate on the date"), "qty", 0.8) \
            .column(t("Carried at"), "num").column(t("Value on the date"), "num").column(t("Difference"), "num")
        for ln in lines:
            rep.row([ln["number"], nm(ln), ln["currency"], ln["residual"], ln["book_rate"], ln["rate"], ln["carrying"],
                     ln["revalued"], ln["diff"]])
        rep.row([t("Net unrealized gain (loss)")] + [None] * 7 + [sum(ln["diff"] for ln in lines)], "grand")
        out = respond(rep, r["number"].replace("/", "-"))
        if out:
            return out
    return render_template("fx/view.html", r=r, lines=lines, branch=branch)


@bp.route("/<int:rid>/cancel", methods=["POST"])
@write_required
def cancel(rid):
    r = q("SELECT * FROM fx_revaluations WHERE id = ?", (rid,), one=True)
    if not r:
        abort(404)
    check_branch(r["branch_id"])
    try:
        cancel_revaluation(rid, user_id())
        commit()
        flash(t("Done."), "success")
    except AccountingError as e:
        get_db().rollback()
        flash(str(e), "error")
        return redirect(url_for("fx.view", rid=rid))
    return redirect(url_for("fx.index", branch=r["branch_id"], date=r["date"]))
