"""Petty cash funds, expense vouchers, top-ups and cash counts."""
from datetime import date
from itertools import zip_longest

from flask import Blueprint, abort, flash, redirect, render_template, request, url_for

from .. import check_branch, context_branch_ids, currency_decimals, login_required, write_required
from ..costcentres import options as cost_centre_options, parse as parse_cost_centre
from ..db import commit, get_db, placeholders, q, x
from ..i18n import t
from ..ledger import AccountingError, audit, now
from ..money import to_int
from ..pettycash import count_cash, create_fund, fund_balance, next_voucher_number, post_voucher, top_up, \
    voucher_totals
from .common import accounts_list, branch_map, default_branch, journals_for, taxes_list, user_id

bp = Blueprint("pettycash", __name__, url_prefix="/petty-cash")


def get_fund(fid):
    f = q("SELECT * FROM petty_cash_funds WHERE id = ?", (fid,), one=True)
    if not f:
        abort(404)
    check_branch(f["branch_id"])
    return f


def get_voucher(vid):
    v = q("SELECT * FROM petty_cash_vouchers WHERE id = ?", (vid,), one=True)
    if not v:
        abort(404)
    return v, get_fund(v["fund_id"])


def currency(branch_id):
    return q("SELECT currency FROM branches WHERE id = ?", (branch_id,), one=True)["currency"]


@bp.route("/")
@login_required
def index():
    ids = context_branch_ids()
    funds = q(f"SELECT * FROM petty_cash_funds WHERE branch_id IN ({placeholders(ids)}) ORDER BY branch_id, id",
              list(ids)) if ids else []
    rows = [dict(f, balance=fund_balance(f), cur=currency(f["branch_id"]),
                 drafts=q("SELECT COUNT(*) FROM petty_cash_vouchers WHERE fund_id = ? AND state = 'draft'", (f["id"],),
                          one=True)[0]) for f in funds]
    return render_template("pettycash/index.html", rows=rows, branches=branch_map(), default_branch=default_branch())


@bp.route("/funds/new", methods=["POST"])
@write_required
def fund_new():
    f = request.form
    try:
        bid = check_branch(f["branch_id"])
        if not f.get("name_en", "").strip():
            raise AccountingError(t("Name (English)") + ": " + t("is required"))
        fid = create_fund(bid, f["name_en"].strip(), f.get("name_ar"), f.get("custodian"), to_int(f.get("float_amount")))
        audit(user_id(), "create", "petty_cash_fund", fid)
        commit()
        flash(t("Petty cash fund created with its own cash account."), "success")
        return redirect(url_for("pettycash.fund", fid=fid))
    except (AccountingError, ValueError, KeyError) as e:
        get_db().rollback()
        flash(str(e), "error")
        return redirect(url_for("pettycash.index"))


@bp.route("/funds/<int:fid>")
@login_required
def fund(fid):
    f = get_fund(fid)
    vouchers = q("SELECT * FROM petty_cash_vouchers WHERE fund_id = ? ORDER BY date DESC, id DESC", (fid,))
    movements = q("SELECT * FROM petty_cash_topups WHERE fund_id = ? ORDER BY date DESC, id DESC", (fid,))
    bal = fund_balance(f)
    acc = q("SELECT * FROM accounts WHERE id = ?", (f["account_id"],), one=True)
    return render_template("pettycash/fund.html", f=f, vouchers=vouchers, movements=movements, balance=bal, acc=acc,
                           cur=currency(f["branch_id"]), banks=journals_for([f["branch_id"]], ["bank"]),
                           suggested=max(f["float_amount"] - bal, 0), today=date.today().isoformat())


@bp.route("/funds/<int:fid>/<action>", methods=["POST"])
@write_required
def fund_action(fid, action):
    f = get_fund(fid)
    fm = request.form
    try:
        d = fm.get("date") or date.today().isoformat()
        if action == "topup":
            top_up(fid, int(fm["bank_journal_id"]), to_int(fm["amount"]), d, user_id())
        elif action == "count":
            if count_cash(fid, to_int(fm["counted"]), d, user_id()) is None:
                flash(t("The cash counted agrees with the books."), "success")
        elif action == "settings":
            x("UPDATE petty_cash_funds SET custodian = ?, float_amount = ?, active = ? WHERE id = ?",
              (fm.get("custodian"), to_int(fm.get("float_amount")), 1 if fm.get("active") else 0, fid))
        else:
            abort(400)
        commit()
        flash(t("Done."), "success")
    except (AccountingError, ValueError, KeyError) as e:
        get_db().rollback()
        flash(str(e), "error")
    return redirect(url_for("pettycash.fund", fid=fid))


def parse_lines(form, decimals):
    rows = zip_longest(form.getlist("account_id"), form.getlist("description"), form.getlist("amount"),
                       form.getlist("tax_id"), form.getlist("cost_centre_id"), form.getlist("receipt_ref"), fillvalue="")
    lines = []
    for acc, desc, amt, tax, cc, ref in rows:
        if not acc and not amt and not desc:
            continue
        if not acc:
            raise AccountingError(t("Every line needs an account."))
        lines.append({"account_id": int(acc), "description": desc, "amount": to_int(amt),
                      "tax_id": int(tax) if tax else None, "cost_centre_id": parse_cost_centre(cc), "receipt_ref": ref})
    if any(ln["amount"] <= 0 for ln in lines):
        raise AccountingError(t("The amount must be greater than zero."))
    return voucher_totals(lines, decimals)


@bp.route("/funds/<int:fid>/vouchers/new", methods=["GET", "POST"])
@bp.route("/vouchers/<int:vid>/edit", methods=["GET", "POST"])
@write_required
def voucher_form(fid=None, vid=None):
    v, f = get_voucher(vid) if vid else (None, get_fund(fid))
    if v and v["state"] != "draft":
        flash(t("Only draft documents can be edited."), "error")
        return redirect(url_for("pettycash.voucher", vid=vid))
    lines = [dict(r) for r in q("SELECT * FROM petty_cash_lines WHERE voucher_id = ? ORDER BY id", (vid,))] if vid else []
    if request.method == "POST":
        fm = request.form
        try:
            lines = parse_lines(fm, currency_decimals(currency(f["branch_id"])))
            if not lines:
                raise AccountingError(t("Add at least one line."))
            total = sum(ln["amount"] + ln["tax_amount"] for ln in lines)
            if v:
                x("UPDATE petty_cash_vouchers SET date = ?, payee = ?, notes = ?, total = ? WHERE id = ?",
                  (fm["date"], fm.get("payee"), fm.get("notes"), total, vid))
                x("DELETE FROM petty_cash_lines WHERE voucher_id = ?", (vid,))
            else:
                vid = x("INSERT INTO petty_cash_vouchers (number, fund_id, branch_id, date, payee, notes, total, state, "
                        "created_by, created_at) VALUES (?,?,?,?,?,?,?, 'draft', ?, ?)",
                        (next_voucher_number(f, fm["date"]), f["id"], f["branch_id"], fm["date"], fm.get("payee"),
                         fm.get("notes"), total, user_id(), now()))
            for ln in lines:
                x("INSERT INTO petty_cash_lines (voucher_id, account_id, description, amount, tax_id, tax_amount, "
                  "cost_centre_id, receipt_ref) VALUES (?,?,?,?,?,?,?,?)",
                  (vid, ln["account_id"], ln["description"], ln["amount"], ln["tax_id"], ln["tax_amount"],
                   ln["cost_centre_id"], ln["receipt_ref"]))
            if fm.get("action") == "post":
                post_voucher(vid, user_id())
            audit(user_id(), "save", "petty_cash", vid)
            commit()
            flash(t("Saved."), "success")
            return redirect(url_for("pettycash.voucher", vid=vid))
        except (AccountingError, ValueError, KeyError) as e:
            get_db().rollback()
            flash(str(e), "error")
            v = dict(fm.items(), id=v["id"] if v else None, number=v["number"] if v else None)
    if not v:
        v = {"date": date.today().isoformat()}
    vat = q("SELECT purchase_tax_id FROM branches WHERE id = ?", (f["branch_id"],), one=True)[0]
    return render_template("pettycash/voucher_form.html", v=v, f=f, lines=lines or [{}, {}, {}],
                           accounts=[a for a in accounts_list() if a["kind"].startswith("expense") or a["kind"] in
                                     ("asset_current", "asset_prepayments")],
                           taxes=taxes_list("purchase"), default_tax=vat, cost_centres=cost_centre_options(),
                           cur=currency(f["branch_id"]), balance=fund_balance(f))


@bp.route("/vouchers/<int:vid>")
@login_required
def voucher(vid):
    v, f = get_voucher(vid)
    lines = q("SELECT l.*, a.code, a.name_en, a.name_ar, tx.name_en AS tname, cc.code AS cc_code FROM petty_cash_lines l "
              "JOIN accounts a ON a.id = l.account_id LEFT JOIN taxes tx ON tx.id = l.tax_id "
              "LEFT JOIN cost_centres cc ON cc.id = l.cost_centre_id WHERE l.voucher_id = ? ORDER BY l.id", (vid,))
    cur = currency(f["branch_id"])
    if request.args.get("export"):
        from ..exports import Report, respond
        from ..i18n import nm
        rep = Report("Petty Cash Voucher", decimals=currency_decimals(cur), signatures=True)
        rep.details = [("Number", v["number"]), ("Date", v["date"]), ("Fund", nm(f)), ("Custodian", f["custodian"] or "—"),
                       ("Paid to", v["payee"] or "—"), ("Status", t(v["state"].capitalize()))]
        rep.column(t("Account"), width=2.2).column(t("Description"), width=2.2).column(t("Receipt no."), width=0.9) \
            .column(t("Amount"), "num").column(t("VAT"), "num").column(t("Total"), "num")
        for ln in lines:
            rep.row([f"{ln['code']}  {nm(ln)}", ln["description"] or "", ln["receipt_ref"] or "", ln["amount"],
                     ln["tax_amount"] or None, ln["amount"] + ln["tax_amount"]])
        rep.totals = [(f"{t('Total')} ({cur})", v["total"], True)]
        if v["notes"]:
            rep.notes.append(v["notes"])
        out = respond(rep, v["number"].replace("/", "-"))
        if out:
            return out
    return render_template("pettycash/voucher.html", v=v, f=f, lines=lines, cur=cur)


@bp.route("/vouchers/<int:vid>/<action>", methods=["POST"])
@write_required
def voucher_action(vid, action):
    v, f = get_voucher(vid)
    try:
        if action == "post":
            post_voucher(vid, user_id())
        elif action == "delete" and v["state"] == "draft":
            x("DELETE FROM petty_cash_vouchers WHERE id = ?", (vid,))
            commit()
            return redirect(url_for("pettycash.fund", fid=f["id"]))
        else:
            raise AccountingError(t("This action is not allowed in the current state."))
        commit()
        flash(t("Done."), "success")
    except AccountingError as e:
        get_db().rollback()
        flash(str(e), "error")
    return redirect(url_for("pettycash.voucher", vid=vid))
