import os
import os.path
import sqlite3
import threading


def traversal_files(_path, _w2t):
    # 功能：以列表的形式分别返回指定路径下的文件和文件夹，不包含子目录
    # 参数：路径
    # 返回值：路径下的文件夹列表 路径下的文件列表
    if not os.path.exists(_path):
        _w2t(f"数据文件夹{_path}不存在，请确认后重试......", "red", "PathNotExistError")
    else:
        dirs, files = [], []
        for item in os.scandir(_path):
            if item.is_dir():
                dirs.append(item.path.replace("\\", "/"))
            elif item.is_file():
                files.append(item.path.replace("\\", "/"))

        return dirs, files


def init_logdb(_conn, _cursor):
    _conn = sqlite3.connect(":memory:", isolation_level=None, check_same_thread=False, cached_statements=4096)
    _cursor = _conn.cursor()
    _cursor.execute("PRAGMA journal_mode=wal")
    _cursor.execute("PRAGMA wal_checkpoint=TRUNCATE")
    _cursor.execute("PRAGMA synchronous=normal")
    _cursor.execute("PRAGMA temp_store=memory")
    _cursor.execute("PRAGMA  mmap_size=30000000000")
    _cursor.execute(
        """
        create table if not exists logs(
            id integer primary key autoincrement,
            time DATETIME DEFAULT(STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW', 'localtime')),
            level text,
            module text,
            content text
        )
        """
    )
    return _conn, _cursor


def db_lock(func):
    def wrapper(*args, **kwargs):
        try:
            lock.acquire(True)
            ret = func(*args, **kwargs)
        finally:
            lock.release()
        return ret

    return wrapper


@db_lock
def insert_logdb(_level, _module, _content):
    if db_state == "readwrite":
        global conn, cursor, lock
        if "move.monitor" in _content:
            return
        data = [_level, _module, repr(_content)]
        cursor.execute("insert into logs (level, module, content) values (?, ?, ?)", data)


def insert_logdb_multi(data):
    if db_state == "readwrite":
        global conn, cursor, lock
        # data = [_level, _module, repr(_content)]
        # cursor.execute("insert into logs (level, module, content) values (?, ?, ?)", data)
        try:
            lock.acquire(True)
            cursor.executemany("insert into logs (level, module, content) values (?, ?, ?)", data)
        finally:
            lock.release()


class GetThreadResult(threading.Thread):
    def __init__(self, func, args=()):
        super(GetThreadResult, self).__init__()
        self.func = func
        self.args = args
        self.result = None

    def run(self):
        self.result = self.func(*self.args)

    def get_result(self):
        threading.Thread.join(self)  # 等待线程执行完毕
        # noinspection PyBroadException
        try:
            return self.result
        except Exception:
            return None


# PREFIX = 'assets'  # for pyinstaller packaging
PREFIX = '../assets'  # for source code testing and debug
log_path = f"{PREFIX}/logs"
conn = None
cursor = None
levels = ["DEBUG", "INFO", "WARNING", "ERROR"]
db_state = "readwrite"
data_dp = {}
data_at = {}
w2t = None
running = False
stop = True
tl_prg = None
f_records = None

ip_addr = "192.168.0.160"
ssh_port = 22
socket_port = 5050
xService_port = 6666
external_port = 8080
modbus_port = 502
upgrade_port = 4567
username = "luoshi"
password = "luoshi2019"  # for real robot
# password = "forpqart"  # for robot vm
interval = 0.5  # interval after actions being triggered, such as modbus/socket/external communication operations
RADIAN = 57.3  # 180 / 3.1415926
MAX_FRAME_SIZE = 1024
c_md = None
c_hr = None
c_ec = None
c_pd = None
lock = threading.Lock()

conn, cursor = init_logdb(conn, cursor)

# ============== ↓↓↓DEBUG CODE↓↓↓ ==============
# for i in range(100):
#     insert_logdb("DEBUG", "clibs", 'running')
#     insert_logdb("INFO", "clibs", 'running')
#     insert_logdb("WARNING", "clibs", 'running')
#     insert_logdb("ERROR", "clibs", 'running')
# with open(f"{log_path}/response.txt", mode="w", encoding="utf-8") as f_res:
#     f_res.write("")
# with open(f"{log_path}/logs.txt", mode="w", encoding="utf-8") as f_res:
#     f_res.write("")
