"""Admin web panel (stdlib HTTP server)."""
import json
import hashlib
import secrets
import time
from http.cookies import SimpleCookie

from . import store

SESSION_COOKIE = "rp_session"


def _hash_token(token):
    return hashlib.sha256(("session:" + token).encode("utf-8")).hexdigest()


def create_session(admin_id, ttl=3600):
    token = secrets.token_urlsafe(32)
    conn = store.connect()
    try:
        conn.execute(
            "INSERT INTO sessions(token_hash,admin_id,expires_at) VALUES(?,?,?)",
            (_hash_token(token), admin_id, int(time.time()) + ttl),
        )
        conn.commit()
    finally:
        conn.close()
    return token


def verify_session(token):
    if not token:
        return None
    conn = store.connect()
    try:
        row = conn.execute(
            "SELECT admin_id FROM sessions WHERE token_hash=? AND expires_at>?",
            (_hash_token(token), int(time.time())),
        ).fetchone()
        return row["admin_id"] if row else None
    finally:
        conn.close()


def destroy_session(token):
    conn = store.connect()
    try:
        conn.execute("DELETE FROM sessions WHERE token_hash=?", (_hash_token(token),))
        conn.commit()
    finally:
        conn.close()


def login(username, password):
    conn = store.connect()
    try:
        row = conn.execute("SELECT * FROM admins WHERE username=? AND enabled=1", (username,)).fetchone()
        if not row:
            return None
        if not store.verify_password(password, row["salt"], row["password_hash"]):
            return None
        return row["id"]
    finally:
        conn.close()


def list_admins():
    conn = store.connect()
    try:
        return conn.execute("SELECT id,username,telegram_id,role,enabled,created_at FROM admins ORDER BY id").fetchall()
    finally:
        conn.close()


def create_admin(username, password, telegram_id=None, role="admin"):
    salt, digest = store.hash_password(password)
    conn = store.connect()
    try:
        cur = conn.execute(
            "INSERT INTO admins (username,password_hash,salt,telegram_id,role,enabled,created_at) VALUES (?,?,?,?,?,1,?)",
            (username, digest, salt, telegram_id, role, time.strftime("%Y-%m-%d %H:%M:%S")),
        )
        conn.commit()
        return cur.lastrowid
    finally:
        conn.close()


def update_admin(admin_id, username=None, password=None, telegram_id=None, enabled=None, role=None):
    conn = store.connect()
    try:
        row = conn.execute("SELECT * FROM admins WHERE id=?", (admin_id,)).fetchone()
        if not row:
            return False
        new_username = username if username is not None else row["username"]
        salt = row["salt"]
        digest = row["password_hash"]
        if password:
            salt, digest = store.hash_password(password)
        conn.execute(
            "UPDATE admins SET username=?, password_hash=?, salt=?, telegram_id=?, enabled=?, role=? WHERE id=?",
            (new_username, digest, salt, telegram_id, enabled if enabled is not None else row["enabled"],
             role if role is not None else row["role"], admin_id),
        )
        conn.commit()
        return True
    finally:
        conn.close()


def delete_admin(admin_id):
    conn = store.connect()
    try:
        conn.execute("UPDATE admins SET enabled=0 WHERE id=?", (admin_id,))
        conn.commit()
        return True
    finally:
        conn.close()