# -*- coding: utf-8 -*-
# Standalone harness: simulate the bot environment for plugins/clients.py
import sqlite3, sys, os

os.chdir('/home/opencode/workspace/isida-ng-v1.01')
sys.path.insert(0, '.')

sqlite_base = os.path.abspath('tmp/test_sqlite.db')
if os.path.exists(sqlite_base):
    os.remove(sqlite_base)

conn = sqlite3.connect(sqlite_base)
cur = conn.cursor()
cur.execute('CREATE TABLE versions (room text, jid text, client text, version text, os text, time integer)')
cur.execute("INSERT INTO versions VALUES ('room@conf','user@host','Miranda IM','0.10.30','Windows NT',1)")
cur.execute("INSERT INTO versions VALUES ('room@conf','user2@host','Pidgin','2.14.12','Linux',1)")
cur.execute("INSERT INTO versions VALUES ('room@conf','user@host','Miranda IM','0.10.30','Windows NT',1)")
conn.commit()

# ---- stubs that are NOT available outside the bot ----
exec_globals = {}
exec(open('plugins/clients.py', encoding='utf-8').read(), exec_globals)
clients_stats = exec_globals['clients_stats']

cur_execute_fetchall = lambda req, params=None: [
    tuple(r) for r in cur.execute(req.replace('%s','?').replace(' ilike ',' like '), params or []).fetchall()
]
def send_msg(mtype, mjid, mnick, mmessage):
    print('SEND[%s][%s]: %s' % (mjid, mnick, mmessage))

class FakeLevel: pass
EXEC = {
    'cur_execute_fetchall': cur_execute_fetchall,
    'send_msg': send_msg,
    'getRoom': lambda j: j.split('/')[0] if j and j != 'None' else ('None'),
    'get_level': lambda room, nick: (4, 'user@host/Resource'),
    'megabase': [['room@conf','user','visitor','none','user@host/Dev'], ['room@conf','user2','member','member','user2@host/X']],
}
EXEC.update(exec_globals)  # function closures reference module globals -> need to inject at module-level of clients source

# clients module defines functions referencing globals at runtime; we exec'd into exec_globals
# The functions resolve globals via the dict they were exec'd into; add our stubs there.
exec_globals['cur_execute_fetchall'] = cur_execute_fetchall
exec_globals['send_msg'] = send_msg
exec_globals['getRoom'] = EXEC['getRoom']
exec_globals['get_level'] = EXEC['get_level']
exec_globals['megabase'] = EXEC['megabase']
exec_globals['L'] = lambda t, jid='': t

tests = [
    ('', ['room@conf', 'nick']),
    ('short', ['room@conf', 'nick']),
    ('os short', ['room@conf', 'nick']),
    ('global', ['room@conf', 'nick']),
    ('global short os', ['room@conf', 'nick']),
    ('user user2', ['room@conf', 'nick']),
    ('Windows', ['room@conf', 'nick']),
]
for text, args in tests:
    print('===== clients %r' % text)
    try:
        clients_stats('groupchat', args[0], args[1], text)
    except Exception as e:
        import traceback; traceback.print_exc()