from __future__ import absolute_import
import sys
import os
import time
import signal
import traceback
import logging
import inspect
import socket
import cwbot.util.DebugThreading as threading
from cwbot.util.DebugThreading import _reset_traceback
from cwbot.processArgv import processArgv
from cwbot.sys.BotSystem import BotSystem
from cwbot.common.exceptions import ManualException, ManualRestartException, \
                                    FatalError
from cwbot.kolextra.manager.ChatManager import ChatManager
from cwbot.kolextra.request.SendMessageRequest import SendMessageRequest
from cwbot.kolextra.manager.InventoryManager import InventoryManager
from cwbot.util.tryRequest import tryRequest
from cwbot.database import database
from kol.Session import Session
import kol.Error
from cwbot.sys.database import Database

exitEvent = threading.Event()
databaseName = 'data/cwbot.db'


def openSession(props):
    """ Log in to the KoL servers. """
    log = logging.getLogger()
    s = Session()
    s.login(props.userName, props.password)
    log.info("Logged in.")
    return s


def createChatManager(s):
    """ Open a new chat manager. """
    log = logging.getLogger()
    log.debug("Opening chat...")    
    c = ChatManager(s)
    log.info("Logged in to chat.")
    return c

    
def createInventoryManager(s, db):
    """ Create a new inventory manager. """
    inv = InventoryManager(s, db)
    return inv


def notifyAdmins(s, props, log, etype, value, tb):
    # kmail the administrators
    if props.debug:
        return
    if s is not None and s.isConnected:
        for uid in props.getAdmins('crash_notify'):