from core import bot
import os, sqlite3, time

prefix = bot.scaledBot.prefix

#Establish a databse connection
if 'plugins' in os.getcwd():
    os.chdir('..')
db_conn = sqlite3.Connection(os.getcwd() + '/data/users.db')
cursor = db_conn.cursor()
try:
    os.chdir('plugins')
except:
    pass

ALIASED_NICKS = []

def get_info(nick):
    nick = nick.lower()
    try:
        info = cursor.execute("""SELECT info FROM users
                              WHERE nick=?""", (nick,)).fetchone()[0]
        if info.split()[0] == 'alias' and info.split()[1]:
            recursive_nick = info.split()[1]
            return get_info(recursive_nick)
        else:
            return info
    except:
        return "Invalid target. Was " + nick + " identified with NickServ when it was !added?"
        ALIASED_NICKS = []

def set_info(nick, info):
    nick = nick.lower()
    cursor.execute("DELETE FROM users WHERE nick=?", (nick,))
    cursor.execute('INSERT INTO users VALUES (?,?)', (nick, info))
    db_conn.commit()

pending_info = {}

onPRIVMSG = bot.scaledBot.lm.get('PRIVMSG')
onNOTICE = bot.scaledBot.lm.get('NOTICE')

@onPRIVMSG.newFunc
def info_handler():
    msg = bot.scaledBot.msg_text
    nick = bot.scaledBot.msg_nick
    channel = bot.scaledBot.msg_channel
    
    if msg.split()[0] in ["!info", "!stalk"]:
        if get_info(msg.split()[1]):
            bot.scaledBot.sendmsg( nick, get_info(msg.split()[1]), msg_type = 'NOTICE')

    elif msg.split()[0] == '@info':
        if get_info(msg.split()[1]):
            bot.scaledBot.sendmsg(channel, msg.split()[1] + ": " + get_info(msg.split()[1]))

    elif msg.split()[0] == prefix + 'add':
        if msg.split()[1]:
            bot.scaledBot.sendmsg('NickServ', 'ACC ' + nick)
            pending_info[nick] = ' '.join(msg.split()[1::])

    elif msg.split()[0] == '!append':
        if msg.split()[1]:
            bot.scaledBot.sendmsg('NickServ', 'ACC ' + nick)
            pending_info[nick] = get_info(nick) + " " + " ".join(msg.split()[1::])

    elif msg.split()[0].lower() == '@slapass':
        bot.scaledBot.sendmsg(channel, "Slapass format: Sex / Location / Age / Picture / Aspirations / Sexuality / Starsign")
        

@onNOTICE.newFunc
def is_identified():
    msg = bot.scaledBot.msg_text
    nick = bot.scaledBot.msg_nick
    channel = bot.scaledBot.msg_channel
    if nick == 'NickServ' and msg.split()[1] == 'ACC' and msg.split()[0] in pending_info.keys():
        if msg.split()[2] == '3':
            set_info(msg.split()[0], pending_info[msg.split()[0]])
            bot.scaledBot.sendmsg(msg.split()[0], 'Your info has been updated successfully.', msg_type = 'NOTICE')
        else:
            bot.scaledBot.sendmsg(msg.split()[0], 'Error: You are not identified with NickServ.', msg_type = 'NOTICE')

            
__name__ = "User Info Manager"
__version__ = '1.2'
__author__ = 'scaled'
