import json
import os
import re
import time
import uuid

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

from .. import admin_required, allowed_branches, has
from ..db import commit, get_db, q
from ..i18n import t
from ..importer import DATE_FORMATS, GROUPS, PREVIEW_COLS, TYPES, auto_map, available_types, clearing_balances, \
    read_file, run, template_csv, template_xlsx, undo, upload_dir
from ..ledger import AccountingError, INVOICE_KINDS, today
from .common import user_id

bp = Blueprint("imports", __name__, url_prefix="/setup/import")

DATED = ("open_items", "entries", "invoices", "payments", "assets")
CUTOFF = ("opening", "stock", "assets")
BRANCHED = ("opening", "open_items", "entries", "invoices", "payments", "stock", "assets")
MASTER = ("accounts", "partners", "products")
DOCUMENTS = ("open_items", "entries", "invoices", "payments", "assets")


def kind_or_404(kind):
    types = available_types(has)
    if kind not in types:
        abort(404)
    return types[kind]


def file_path(token):
    if not re.fullmatch(r"[0-9a-f]{32}", token or ""):
        abort(404)
    folder = upload_dir(current_app.config["DATABASE"])
    for ext in (".xlsx", ".xlsm", ".csv"):
        p = os.path.join(folder, token + ext)
        if os.path.exists(p):
            meta = {}
            if os.path.exists(os.path.join(folder, token + ".json")):
                with open(os.path.join(folder, token + ".json"), encoding="utf-8") as fh:
                    meta = json.load(fh)
            return p, meta
    abort(404)


def remove_upload(token):
    folder = upload_dir(current_app.config["DATABASE"])
    for ext in (".xlsx", ".xlsm", ".csv", ".json"):
        p = os.path.join(folder, token + ext)
        if os.path.exists(p):
            os.remove(p)


def clean_old_uploads():
    folder = upload_dir(current_app.config["DATABASE"])
    for name in os.listdir(folder):
        p = os.path.join(folder, name)
        if os.path.isfile(p) and time.time() - os.path.getmtime(p) > 2 * 86400:
            os.remove(p)


def default_options(kind):
    branches = allowed_branches()
    return {"date_format": "DD/MM/YYYY", "header_row": 1, "update_existing": True, "create_partners": True,
            "skip_existing": True, "role": "customer",
            "doc_kind": "out_invoice", "cutoff": "", "branch_id": branches[0]["id"] if len(branches) == 1 else "",
            "redirect_ar": True, "redirect_stock": has("inventory"), "redirect_assets": has("assets"),
            "difference_account": "", "sheet": ""}


def read_options(form, kind):
    o = default_options(kind)
    for k in ("date_format", "role", "doc_kind", "cutoff", "branch_id", "difference_account", "sheet"):
        if k in form:
            o[k] = form.get(k, "").strip()
    o["header_row"] = int(form.get("header_row") or 1) if (form.get("header_row") or "1").isdigit() else 1
    for k in ("update_existing", "create_partners", "skip_existing", "redirect_ar", "redirect_stock", "redirect_assets"):
        o[k] = bool(form.get(k))
    if o["date_format"] not in DATE_FORMATS:
        o["date_format"] = "DD/MM/YYYY"
    return o


@bp.route("/")
@admin_required
def index():
    types = available_types(has)
    batches = q("SELECT b.*, u.username FROM import_batches b LEFT JOIN users u ON u.id = b.created_by "
                "ORDER BY b.id DESC LIMIT 100")
    ids = [b["id"] for b in allowed_branches()]
    return render_template("imports/index.html", types=types, groups=GROUPS, batches=batches,
                           clearing=clearing_balances(ids))


@bp.route("/template/<kind>.<fmt>")
@admin_required
def template(kind, fmt):
    m = kind_or_404(kind)
    name = re.sub(r"[^A-Za-z0-9]+", "-", m["title"]).strip("-").lower()
    if fmt == "csv":
        return Response(template_csv(kind), mimetype="text/csv; charset=utf-8",
                        headers={"Content-Disposition": f"attachment; filename=vertex-{name}.csv"})
    if fmt == "xlsx":
        return Response(template_xlsx(kind),
                        mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                        headers={"Content-Disposition": f"attachment; filename=vertex-{name}.xlsx"})
    abort(404)


@bp.route("/<kind>", methods=["GET", "POST"])
@admin_required
def upload(kind):
    m = kind_or_404(kind)
    if request.method == "POST":
        f = request.files.get("file")
        if not f or not f.filename:
            flash(t("Choose a file."), "error")
            return redirect(request.url)
        ext = os.path.splitext(f.filename)[1].lower()
        if ext == ".xls":
            flash(t("Old .xls files are not supported. Open the file in Excel and save it as .xlsx or .csv."), "error")
            return redirect(request.url)
        if ext not in (".xlsx", ".xlsm", ".csv", ".txt"):
            flash(t("Upload an Excel (.xlsx) or CSV file."), "error")
            return redirect(request.url)
        clean_old_uploads()
        token = uuid.uuid4().hex
        folder = upload_dir(current_app.config["DATABASE"])
        f.save(os.path.join(folder, token + (".csv" if ext == ".txt" else ext)))
        with open(os.path.join(folder, token + ".json"), "w", encoding="utf-8") as fh:
            json.dump({"filename": f.filename, "header_row": request.form.get("header_row") or "1"}, fh)
        return redirect(url_for("imports.mapping", kind=kind, token=token))
    return render_template("imports/upload.html", kind=kind, m=m)


@bp.route("/<kind>/<token>", methods=["GET", "POST"])
@admin_required
def mapping(kind, token):
    m = kind_or_404(kind)
    path, meta = file_path(token)
    form = request.form if request.method == "POST" else {}
    options = read_options(form, kind) if form else dict(default_options(kind), header_row=int(meta.get("header_row") or 1))
    try:
        header, rows, sheets = read_file(path, options["header_row"], options["sheet"] or None)
    except (AccountingError, ValueError) as e:
        flash(str(e), "error")
        return redirect(url_for("imports.upload", kind=kind))
    if form and form.get("remap") != "1":
        mapping_ = {}
        for f in m["fields"]:
            v = form.get("map_" + f["key"], "")
            if v.isdigit() and int(v) < len(header):
                mapping_[f["key"]] = int(v)
    else:
        mapping_ = auto_map(kind, header)
    action = form.get("action") if form else (None if kind in CUTOFF else "check")
    if g.user["role"] == "admin" or g.user["all_branches"]:
        options["allowed_branches"] = None
    else:
        options["allowed_branches"] = [b["id"] for b in allowed_branches()]
    result = None
    if action in ("check", "import"):
        try:
            result = run(kind, rows, mapping_, options, user_id(), meta.get("filename", ""),
                         commit_changes=(action == "import"))
        except AccountingError as e:
            result = None
            flash(str(e), "error")
        if action == "import" and result is not None and getattr(result, "batch_id", None):
            remove_upload(token)
            flash(t("Import complete") + f": {result.created} {t('created')}, {result.updated} {t('updated')}"
                  + (f", {result.skipped} {t('skipped')}" if result.skipped else "") + ".", "success")
            return redirect(url_for("imports.index"))
        if action == "import" and result is not None and not result.errors:
            flash(t("Nothing to import."), "error")
    from .setup import opt_accounts
    return render_template("imports/mapping.html", kind=kind, m=m, token=token, meta=meta, header=header,
                           rows=rows, sheets=sheets, mapping=mapping_, options=options, result=result,
                           formats=list(DATE_FORMATS), branches=allowed_branches(), accounts=opt_accounts(),
                           preview_cols=PREVIEW_COLS[kind], dated=kind in DATED, cutoff=kind in CUTOFF,
                           branched=kind in BRANCHED, master=kind in MASTER, documents=kind in DOCUMENTS,
                           doc_kinds=[(k, v["label"]) for k, v in INVOICE_KINDS.items()], today=today())


@bp.route("/batch/<int:bid>/undo", methods=["POST"])
@admin_required
def undo_batch(bid):
    try:
        undo(bid, user_id())
        commit()
        flash(t("The import was undone."), "success")
    except AccountingError as e:
        get_db().rollback()
        flash(str(e), "error")
    return redirect(url_for("imports.index"))
