"""My Approvals (inbox, notifications, out-of-office delegation) and the workflow setup: approval roles, approval
rules with their steps, and the terms & conditions library."""
from datetime import date

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

from .. import admin_required, has, login_required
from ..db import commit, get_db, q, x
from ..i18n import t
from ..ledger import AccountingError, audit, now
from ..money import to_int
from ..projects import options as project_options
from ..workflow import DOC_TYPES, TERMS_TYPES, act, doc_types, inbox
from .common import branch_map, user_id

bp = Blueprint("workflow", __name__)


def users_list():
    return q("SELECT id, username, full_name, email, role FROM users WHERE active = 1 ORDER BY full_name, username")


# ---------------------------------------------------------------- my approvals

@bp.route("/approvals")
@login_required
def inbox_view():
    uid = user_id()
    tasks = inbox(uid)
    notes = q("SELECT * FROM notifications WHERE user_id = ? ORDER BY id DESC LIMIT 40", (uid,))
    today = date.today().isoformat()
    delegations = q("SELECT d.*, u.full_name, u.username FROM approval_delegations d JOIN users u ON u.id = d.delegate_id "
                    "WHERE d.user_id = ? AND d.date_to >= ? ORDER BY d.date_from", (uid, today))
    mine = q("SELECT r.*, (SELECT name FROM approval_steps s WHERE s.rule_id = r.rule_id AND s.step_no = r.current_step) "
             "AS step_name FROM approval_requests r WHERE r.requested_by = ? AND r.state = 'pending' ORDER BY r.id DESC",
             (uid,))
    return render_template("workflow/inbox.html", tasks=tasks, notes=notes, delegations=delegations, mine=mine,
                           users=[u for u in users_list() if u["id"] != uid], types=DOC_TYPES, today=today,
                           branches=branch_map())


@bp.route("/approvals/<int:request_id>/<action>", methods=["POST"])
@login_required
def decide(request_id, action):
    if action not in ("approve", "reject"):
        abort(404)
    try:
        act(request_id, user_id(), action, request.form.get("comment"))
        commit()
        flash(t("Approved.") if action == "approve" else t("Rejected."), "success")
    except AccountingError as e:
        get_db().rollback()
        flash(str(e), "error")
    return redirect(request.referrer or url_for("workflow.inbox_view"))


@bp.route("/approvals/notifications/read", methods=["POST"])
@login_required
def read_all():
    x("UPDATE notifications SET read_at = ? WHERE user_id = ? AND read_at IS NULL", (now(), user_id()))
    commit()
    return redirect(url_for("workflow.inbox_view"))


@bp.route("/approvals/notifications/<int:nid>")
@login_required
def open_note(nid):
    n = q("SELECT * FROM notifications WHERE id = ? AND user_id = ?", (nid, user_id()), one=True)
    if not n:
        abort(404)
    x("UPDATE notifications SET read_at = COALESCE(read_at, ?) WHERE id = ?", (now(), nid))
    commit()
    url = n["url"] or url_for("workflow.inbox_view")
    # links in emails carry the public address; inside the app go to the path
    if "://" in url:
        url = "/" + url.split("://", 1)[1].split("/", 1)[-1]
    return redirect(url)


@bp.route("/approvals/delegate", methods=["POST"])
@login_required
def delegate():
    f = request.form
    try:
        did = int(f["delegate_id"])
        if did == user_id():
            raise AccountingError(t("Choose another person."))
        if f["date_to"] < f["date_from"]:
            raise AccountingError(t("The end date is before the start date."))
        x("INSERT INTO approval_delegations (user_id, delegate_id, date_from, date_to, reason, created_at) "
          "VALUES (?,?,?,?,?,?)", (user_id(), did, f["date_from"], f["date_to"], f.get("reason"), now()))
        audit(user_id(), "delegate", "user", did, f"{f['date_from']} → {f['date_to']}")
        commit()
        flash(t("Your approvals go to the delegate for those dates."), "success")
    except (AccountingError, KeyError, ValueError) as e:
        get_db().rollback()
        flash(str(e), "error")
    return redirect(url_for("workflow.inbox_view"))


@bp.route("/approvals/delegate/<int:did>/delete", methods=["POST"])
@login_required
def delegate_delete(did):
    x("DELETE FROM approval_delegations WHERE id = ? AND user_id = ?", (did, user_id()))
    commit()
    return redirect(url_for("workflow.inbox_view"))


# ---------------------------------------------------------------- setup: roles

@bp.route("/setup/workflow")
@admin_required
def rules():
    rows = q("SELECT r.*, b.code AS bcode FROM approval_rules r LEFT JOIN branches b ON b.id = r.branch_id "
             "ORDER BY r.doc_type, r.priority, r.min_amount")
    steps = {}
    for s in q("SELECT s.*, ro.name_en AS role_en, ro.name_ar AS role_ar FROM approval_steps s "
               "LEFT JOIN approval_roles ro ON ro.id = s.role_id ORDER BY s.step_no"):
        if s["dynamic"] == "project_manager" and not has("projects"):
            continue  # applies only with the Projects module
        steps.setdefault(s["rule_id"], []).append(s)
    roles = q("SELECT ro.*, (SELECT COUNT(*) FROM approval_role_users WHERE role_id = ro.id) AS n FROM approval_roles ro "
              "ORDER BY ro.name_en")
    from ..ledger import company
    return render_template("workflow/rules.html", rows=rows, steps=steps, types=doc_types(), all_types=DOC_TYPES,
                           roles=roles, currency=company()["currency"])


@bp.route("/setup/workflow/rule/new", methods=["GET", "POST"])
@bp.route("/setup/workflow/rule/<int:rid>", methods=["GET", "POST"])
@admin_required
def rule_form(rid=None):
    r = q("SELECT * FROM approval_rules WHERE id = ?", (rid,), one=True) if rid else None
    if rid and not r:
        abort(404)
    if request.method == "POST":
        f = request.form
        try:
            if f.get("action") == "delete" and r:
                if q("SELECT 1 FROM approval_requests WHERE rule_id = ? AND state = 'pending'", (rid,), one=True):
                    raise AccountingError(t("Documents are waiting under this rule; switch it off instead."))
                x("UPDATE approval_requests SET rule_id = NULL WHERE rule_id = ?", (rid,))
                x("DELETE FROM approval_rules WHERE id = ?", (rid,))
                audit(user_id(), "delete", "approval_rule", rid, r["name"])
                commit()
                return redirect(url_for("workflow.rules"))
            if f.get("doc_type") not in doc_types():
                raise AccountingError(t("Choose the document type."))
            vals = {"doc_type": f["doc_type"], "name": (f.get("name") or "").strip(),
                    "branch_id": int(f["branch_id"]) if f.get("branch_id") else None,
                    "department": (f.get("department") or "").strip() or None,
                    "project_id": int(f["project_id"]) if f.get("project_id") and has("projects") else None,
                    "min_amount": to_int(f.get("min_amount") or 0),
                    "max_amount": to_int(f["max_amount"]) if (f.get("max_amount") or "").strip() else None,
                    "priority": int(f.get("priority") or 10), "reminder_days": int(f.get("reminder_days") or 2),
                    "active": 1 if f.get("active") else 0}
            if not vals["name"]:
                raise AccountingError(t("Give the rule a name."))
            if vals["max_amount"] is not None and vals["max_amount"] < vals["min_amount"]:
                raise AccountingError(t("The upper amount is below the lower amount."))
            steps = []
            for i in range(1, 7):
                name = (f.get(f"s{i}_name") or "").strip()
                role = f.get(f"s{i}_role")
                users = [int(u) for u in f.getlist(f"s{i}_users") if u]
                if not (name or role or users):
                    continue
                if not (role or users):
                    raise AccountingError(f"{t('Step')} {i}: {t('choose a role or approvers')}")
                dynamic = None
                if role == "pm":
                    if not has("projects"):
                        raise AccountingError(f"{t('Step')} {i}: {t('choose a role or approvers')}")
                    dynamic, role = "project_manager", None
                mode = f.get(f"s{i}_mode") if f.get(f"s{i}_mode") in ("any", "all") else "any"
                steps.append({"name": name or f"{t('Step')} {len(steps) + 1}", "role_id": int(role) if role else None,
                              "users": users, "mode": mode, "required": max(int(f.get(f"s{i}_required") or 1), 1),
                              "dynamic": dynamic})
            if not steps:
                raise AccountingError(t("Add at least one approval step."))
            if r:
                x(f"UPDATE approval_rules SET {', '.join(k + ' = ?' for k in vals)} WHERE id = ?", list(vals.values()) + [rid])
                x("DELETE FROM approval_steps WHERE rule_id = ?", (rid,))
            else:
                rid = x(f"INSERT INTO approval_rules ({', '.join(vals)}) VALUES ({', '.join('?' * len(vals))})",
                        list(vals.values()))
            for n, s in enumerate(steps, 1):
                sid = x("INSERT INTO approval_steps (rule_id, step_no, name, mode, required, role_id, dynamic) "
                        "VALUES (?,?,?,?,?,?,?)", (rid, n, s["name"], s["mode"], s["required"], s["role_id"], s["dynamic"]))
                for u in s["users"]:
                    x("INSERT INTO approval_step_users (step_id, user_id) VALUES (?,?)", (sid, u))
            audit(user_id(), "save", "approval_rule", rid, vals["name"])
            commit()
            flash(t("Saved."), "success")
            return redirect(url_for("workflow.rules"))
        except (AccountingError, ValueError) as e:
            get_db().rollback()
            flash(str(e), "error")
            r = dict(f.items())
    steps = []
    if rid:
        for s in q("SELECT * FROM approval_steps WHERE rule_id = ? ORDER BY step_no", (rid,)):
            if s["dynamic"] == "project_manager" and not has("projects"):
                continue
            steps.append(dict(s, users=[u[0] for u in q("SELECT user_id FROM approval_step_users WHERE step_id = ?",
                                                        (s["id"],))]))
    return render_template("workflow/rule_form.html", r=r or {"active": 1, "priority": 10, "reminder_days": 2,
                                                               "doc_type": request.args.get("doc_type", "po")},
                           steps=steps, types=doc_types(), branches=branch_map(),
                           projects=project_options(dict(r).get("project_id") if r else None),
                           roles=q("SELECT * FROM approval_roles WHERE active = 1 ORDER BY name_en"), users=users_list())


@bp.route("/setup/workflow/roles", methods=["GET", "POST"])
@admin_required
def roles():
    if request.method == "POST":
        f = request.form
        try:
            if f.get("action") == "delete":
                rid = int(f["role_id"])
                if q("SELECT 1 FROM approval_steps WHERE role_id = ?", (rid,), one=True):
                    raise AccountingError(t("The role is used by an approval rule."))
                x("DELETE FROM approval_roles WHERE id = ?", (rid,))
            else:
                name = (f.get("name_en") or "").strip()
                if not name:
                    raise AccountingError(t("Name (English)") + ": " + t("is required"))
                if f.get("role_id"):
                    rid = int(f["role_id"])
                    x("UPDATE approval_roles SET name_en = ?, name_ar = ? WHERE id = ?", (name, f.get("name_ar"), rid))
                    x("DELETE FROM approval_role_users WHERE role_id = ?", (rid,))
                else:
                    rid = x("INSERT INTO approval_roles (name_en, name_ar) VALUES (?,?)", (name, f.get("name_ar")))
                for u in f.getlist("users"):
                    x("INSERT INTO approval_role_users (role_id, user_id) VALUES (?,?)", (rid, int(u)))
            audit(user_id(), "save", "approval_role", None, f.get("name_en"))
            commit()
            flash(t("Saved."), "success")
        except (AccountingError, ValueError, KeyError) as e:
            get_db().rollback()
            flash(str(e), "error")
        return redirect(url_for("workflow.roles"))
    rows = q("SELECT * FROM approval_roles ORDER BY name_en")
    members = {}
    for m in q("SELECT ru.role_id, u.id, u.full_name, u.username FROM approval_role_users ru JOIN users u ON u.id = ru.user_id"):
        members.setdefault(m["role_id"], []).append(m)
    edit = q("SELECT * FROM approval_roles WHERE id = ?", (request.args.get("edit", type=int),), one=True)
    return render_template("workflow/roles.html", rows=rows, members=members, users=users_list(), edit=edit,
                           edit_members=[m["id"] for m in members.get(edit["id"], [])] if edit else [])


# ---------------------------------------------------------------- setup: terms and conditions

@bp.route("/setup/terms", methods=["GET", "POST"])
@admin_required
def terms():
    if request.method == "POST":
        f = request.form
        try:
            if f.get("action") == "delete":
                x("DELETE FROM terms_templates WHERE id = ?", (int(f["tid"]),))
            else:
                if f.get("doc_type") not in TERMS_TYPES or not (f.get("name") or "").strip():
                    raise AccountingError(t("Give the template a name and a document type."))
                vals = (f["name"].strip(), f["doc_type"], f.get("body_en"), f.get("body_ar"),
                        1 if f.get("is_default") else 0)
                if vals[4]:
                    x("UPDATE terms_templates SET is_default = 0 WHERE doc_type = ?", (f["doc_type"],))
                if f.get("tid"):
                    x("UPDATE terms_templates SET name = ?, doc_type = ?, body_en = ?, body_ar = ?, is_default = ? "
                      "WHERE id = ?", vals + (int(f["tid"]),))
                else:
                    x("INSERT INTO terms_templates (name, doc_type, body_en, body_ar, is_default) VALUES (?,?,?,?,?)", vals)
            commit()
            flash(t("Saved."), "success")
        except (AccountingError, ValueError, KeyError) as e:
            get_db().rollback()
            flash(str(e), "error")
        return redirect(url_for("workflow.terms"))
    rows = q("SELECT * FROM terms_templates ORDER BY doc_type, is_default DESC, name")
    edit = q("SELECT * FROM terms_templates WHERE id = ?", (request.args.get("edit", type=int),), one=True)
    return render_template("workflow/terms.html", rows=rows, types=TERMS_TYPES, edit=edit)
