"""Warehouse transfers: stock moved between warehouses, inside a branch or to another branch."""
from datetime import date

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

from .. import allowed_branch_ids, check_branch, context_branch_ids, login_required, module_required, write_required
from ..db import commit, get_db, placeholders, q, x
from ..i18n import t
from ..ledger import AccountingError
from ..wtransfers import create, receive, return_to_sender, send
from .common import branch_map, user_id

bp = Blueprint("wtransfers", __name__, url_prefix="/stock-transfers")
bp.before_request(module_required("inventory"))
STATES = {"draft": "Draft", "in_transit": "In transit", "done": "Done", "cancelled": "Cancelled"}


def get_transfer(tid):
    tr = q("SELECT * FROM stock_transfers WHERE id = ?", (tid,), one=True)
    if not tr:
        abort(404)
    ids = allowed_branch_ids()
    if tr["branch_id"] not in ids and tr["to_branch_id"] not in ids:
        abort(403)
    return tr


def warehouses():
    ids = allowed_branch_ids()
    return q(f"SELECT w.*, b.code AS bcode, b.currency FROM warehouses w JOIN branches b ON b.id = w.branch_id "
             f"WHERE w.active = 1 AND w.branch_id IN ({placeholders(ids)}) ORDER BY b.code, w.code", list(ids)) if ids else []


@bp.route("/")
@login_required
def index():
    ids = context_branch_ids()
    rows = q(f"SELECT tr.*, wf.code AS from_code, wt.code AS to_code, "
             f"(SELECT COALESCE(SUM(value), 0) FROM stock_transfer_lines WHERE transfer_id = tr.id) AS value, "
             f"(SELECT COUNT(*) FROM stock_transfer_lines WHERE transfer_id = tr.id) AS n "
             f"FROM stock_transfers tr JOIN warehouses wf ON wf.id = tr.from_warehouse_id "
             f"JOIN warehouses wt ON wt.id = tr.to_warehouse_id WHERE tr.branch_id IN ({placeholders(ids)}) "
             f"OR tr.to_branch_id IN ({placeholders(ids)}) ORDER BY tr.date DESC, tr.id DESC",
             list(ids) * 2) if ids else []
    return render_template("wtransfers/list.html", rows=rows, states=STATES, branches=branch_map())


@bp.route("/new", methods=["GET", "POST"])
@write_required
def form():
    whs = warehouses()
    if request.method == "POST":
        f = request.form
        try:
            src = int(f["from_warehouse_id"])
            if src not in [w["id"] for w in whs] or int(f["to_warehouse_id"]) not in [w["id"] for w in whs]:
                abort(403)
            lines = [{"product_id": int(p), "quantity": float(qq or 0)}
                     for p, qq in zip(f.getlist("product_id"), f.getlist("quantity")) if p]
            tid = create(src, int(f["to_warehouse_id"]), f["date"], lines, f.get("notes"), user_id())
            if f.get("action") == "send":
                send(tid, f["date"], user_id())
            commit()
            flash(t("Saved."), "success")
            return redirect(url_for("wtransfers.view", tid=tid))
        except (AccountingError, ValueError, KeyError) as e:
            get_db().rollback()
            flash(str(e), "error")
    stock = {}
    for r in q("SELECT product_id, warehouse_id, qty FROM stock_quants WHERE qty > 0"):
        stock.setdefault(r["warehouse_id"], {})[r["product_id"]] = r["qty"]
    return render_template("wtransfers/form.html", warehouses=whs, stock=stock, today=date.today().isoformat(),
                           products=q("SELECT * FROM products WHERE type = 'stock' AND active = 1 ORDER BY code"))


@bp.route("/<int:tid>")
@login_required
def view(tid):
    tr = get_transfer(tid)
    lines = q("SELECT l.*, p.code, p.name_en, p.name_ar FROM stock_transfer_lines l JOIN products p ON p.id = l.product_id "
              "WHERE l.transfer_id = ? ORDER BY l.id", (tid,))
    wf = q("SELECT w.*, b.currency, b.code AS bcode FROM warehouses w JOIN branches b ON b.id = w.branch_id WHERE w.id = ?",
           (tr["from_warehouse_id"],), one=True)
    wt = q("SELECT w.*, b.currency, b.code AS bcode FROM warehouses w JOIN branches b ON b.id = w.branch_id WHERE w.id = ?",
           (tr["to_warehouse_id"],), one=True)
    return render_template("wtransfers/view.html", tr=tr, lines=lines, wf=wf, wt=wt, states=STATES,
                           today=date.today().isoformat())


@bp.route("/<int:tid>/<action>", methods=["POST"])
@write_required
def action(tid, action):
    tr = get_transfer(tid)
    d = request.form.get("date") or date.today().isoformat()
    try:
        if action == "send":
            check_branch(tr["branch_id"])
            send(tid, d, user_id())
        elif action == "receive":
            check_branch(tr["to_branch_id"])
            receive(tid, d, user_id())
        elif action == "return":
            check_branch(tr["branch_id"])
            return_to_sender(tid, d, user_id())
        elif action == "delete" and tr["state"] == "draft":
            x("DELETE FROM stock_transfers WHERE id = ?", (tid,))
            commit()
            return redirect(url_for("wtransfers.index"))
        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("wtransfers.view", tid=tid))
