# -*- coding:utf-8 -*-
"""
@Author  : xuxingchen
@Contact : xuxingchen@sinochem.com
@Desc    : 记录一些会话数据
"""
import time

from utils.database import BaseTable


class SessionsTable(BaseTable):
    @staticmethod
    def check(table_handler: BaseTable):
        """检测是否存在当前表"""
        table_handler.query("SELECT name FROM sqlite_master WHERE type='table' AND name='sessions'")
        if table_handler.cursor.fetchone() is None:
            table_handler.execute(
                f"""
                CREATE TABLE sessions (
                    session_id TEXT,
                    username TEXT,
                    token TEXT,
                    captcha TEXT,
                    last_timestamp TEXT,
                    PRIMARY KEY (session_id)
                )
                """
            )
            table_handler.execute(
                f"""
                CREATE INDEX idx_sessions_token ON sessions(token);
                """
            )
        # 去除冗余的验证会话信息
        table_handler.execute(
            f"""
            DELETE FROM sessions WHERE last_timestamp < {int(time.time() * 1000) - 3 * 24 * 60 * 60 * 1000}
            """
        )

    @staticmethod
    def get_captcha(table_handler: BaseTable, session_id: str):
        table_handler.query(
            """
            SELECT captcha
            FROM sessions
            WHERE session_id = ?
            """,
            (session_id,),
        )
        res = table_handler.cursor.fetchall()
        if res:
            return res[0][0]
        else:
            return None

    @staticmethod
    def insert(table_handler: BaseTable, session_id, captcha):
        timestamp = str(int(time.time() * 1000))
        table_handler.execute(
            """
            INSERT INTO sessions 
            (session_id, captcha, last_timestamp)
            VALUES (?, ?, ?)
            ON CONFLICT (session_id)
            DO UPDATE SET captcha=?, last_timestamp=?
            """,
            (
                session_id,
                captcha,
                timestamp,
                captcha,
                timestamp,
            ),
        )
        return True

    @staticmethod
    def update(table_handler: BaseTable, session_id: str, username: str, token: str):
        timestamp = str(int(time.time() * 1000))
        table_handler.execute(
            """
            UPDATE sessions SET 
            username=?,
            token=?,
            last_timestamp=?
            WHERE session_id=?
            """,
            (
                username,
                token,
                timestamp,
                session_id
            ),
        )
        return True

    @staticmethod
    def check_token(table_handler: BaseTable, timestamp: str, token: str):
        table_handler.query(
            """
            SELECT captcha
            FROM sessions
            WHERE last_timestamp > ? and token = ? 
            """,
            (timestamp, token),
        )
        res = table_handler.cursor.fetchall()
        if res:
            return True
        else:
            return False
