from aiogram import types, Dispatcher
#from sqlalchemy.orm.session import close_all_sessions
from create_bot import bot, dp
#from sqdb import user, session
import random
from random import randint
import datetime
from dicktxt import ForReadDict


#### https://docs.python-arango.com/en/main/
from arango import ArangoClient
 


@dp.message_handler(commands=["dick"])
async def up_dick(message: types.Message):
    #global size_change, dick_plus, dick_minus

    
    arango_client = ArangoClient(hosts='https://arango.vdk2ch.ru') 
    pipisa_db     = arango_client.db('pipisa', username='root', password='stolendick527') 
    dicks_collection = pipisa_db.collection('dicks') 


    # рандомайзер
    numb = randint(-9,10)
    dick_plus  = (
        '<b>вырос</b>',
        '<b>подрос</b>',
        '<b>привстал</b>',
        '<b>увеличился</b>',
        '<b>преисполнился</b>'
    )
    dick_minus = (
        '<b>неудачно потусил на сходке</b>',
        '<b>уменьшился</b>',
        '<b>откусила злая гадюка</b>',
        '<b>продали евреи, он стал дешевле</b>'
    )

    if numb > 0:
        size_change  = random.choice(dick_plus) + '🚀'
	#if numb = 0 size_change = random.choice(const)  TODO
    else: 
        size_change = random.choice(dick_minus) + '✂'


    try:
        #### Чекнуть есть ли юзер в базе
        candidate_cursor = dicks_collection.find(
            {
                'user_id': message.from_user.id,
                'chat_id': message.chat.id
            },
            skip=0, limit=1488)

        if candidate_cursor.count() > 0: 
            ## Если есть то нарастить и отправить сообщение

            user = candidate_cursor.pop()

            last_time    = datetime.datetime.strptime(user['datetimes'], '%Y-%m-%d %H:%M:%S')
            time_to_grow = datetime.datetime.now().replace(hour=14, minute=8, second=8, microsecond=0)

            if (time_to_grow - last_time).total_seconds() > 0:
                # пришло время крутить!!
 
                updetedDick = user["dick_size"] + numb 
                try:
                    dt = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                    metadata = dicks_collection.insert(
                        {
                            '_key':          user['_key'],
                            '_id':           user['_id'],
                            '_rev':          user['_rev'],
                            'user_id':       message.from_user.id,
                            'user_fullname': user['user_fullname'],
                            'dick_size':     updetedDick,
                            'datetimes':     datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                            'attempts':      user['attempts'] + 1,
                            'chat_id':       message.chat.id
                        },
                        overwrite_mode='update'
                    )
                    print(f'Успешно апдейтнули пипису @{message.from_user.username}') 
                except Exception as e2:
                    print(f'ошибка в обновлении пиписы @{message.from_user.username}')
                    print(e2) 

                randomword  = ForReadDict.RandomDick()


                await bot.send_message(message.chat.id, f'@{message.from_user.username}, ваш <em>{randomword}</em> {size_change}\
на <b>{abs(numb)}</b> см!\n\
Теперь он равен <b>{updetedDick}</b> см! ')
            else:
                await bot.send_message(message.chat.id, f'@{message.from_user.username},🚫 вы уже крутили пипису, ее размер <b>{user["dick_size"]}</b> см! ')
                
                try:
                    metadata = dicks_collection.insert(
                        {
                            '_key':          user['_key'],
                            '_id':           user['_id'],
                            '_rev':          user['_rev'],
                            'user_id':       user['attempts'] ,
                            'user_fullname': user['user_fullname'],
                            'dick_size':     user['attempts'] ,
                            'datetimes':     user['datetimes'] ,
                            'attempts':      user['attempts'] + 1,
                            'chat_id':       message.chat.id
                        },
                        overwrite_mode='update'
                    )
                    print(f'Успешно апдейтнули попытку крутить пипису @{message.from_user.username}') 
                except Exception as e2:
                    print(f'ошибка в обновлении попытки крутить пипису @{message.from_user.username}')
                    print(e2) 

                print(f'пользователь @{message.from_user.username} уже крутил')

        else: 
            ## если нету, то создать 
 
            try: 
                novenkiy = {
                    'user_id':       message.from_user.id,
                    'user_fullname': message.from_user.full_name,
                    'dick_size':     numb,
                    'datetimes':     datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                    'attempts':      1,
                    'chat_id':       message.chat.id
                }

                #### TODO проверить как-то по-умному что мы таки его добавили
                metadata = dicks_collection.insert(novenkiy, overwrite_mode='update')
              

                if numb > 0:
                    await bot.send_message(message.chat.id, f'@{message.from_user.username}, ваш писюн показал головку 🚀\n\
на <b>{abs(numb)}</b> см!\n\
Теперь он равен <b>{numb}</b> см!') 
                else:
                    await bot.send_message(message.chat.id, f'@{message.from_user.username}, добро пожаловать в игру!🚀\n\
Ты стартуешь не с лучшей позиции, природа наградила тебя всего <b>{numb}</b> см 😬')
                    
                    
                print(f'Успешно добавлен пользователь @{message.from_user.username}')
            except Exception as e1:
                print('ошибка в добавлении нового пользователя')
                print(e1) 


    except Exception as e: 
        print('ошибка DB в /dick')
        print(e)
 
 
        
    
@dp.message_handler(commands=["topdick"])
async def send_topchat(message: types.Message):


    arango_client = ArangoClient(hosts='https://arango.vdk2ch.ru') 
    pipisa_db     = arango_client.db('pipisa', username='root', password='stolendick527') 
    dicks_collection = pipisa_db.collection('dicks') 

    try:
        dicks = dicks_collection.find({'chat_id': message.chat.id}, skip=0, limit=1100)
        dicks = [d for d in dicks]
    except Exception as e: 
        print('ошибка DB в /topdick')
        print(e)

    top_dicks  = sorted(dicks, key=lambda dick: dick['dick_size'], reverse=True)
    
    dick_limit = min(len(top_dicks), 10)
    top_dicks  = top_dicks[:dick_limit]
  
    dickos = ''
    emo    = ['🏆','🚀','🍆','🍌','🐍','🐎','🌭','🌶','👌','💩']

    if len(top_dicks) == 0:
        await bot.send_message(message.chat.id, '🍆 Никто ничего не нарастил! 🍌')
    else:
        for i in range(len(top_dicks)): 
            dickos += f'     {emo[i]} {i+1}. {top_dicks[i]["user_fullname"]}: {top_dicks[i]["dick_size"]}см\n'
            i += 1

        await bot.send_message(message.chat.id, '🏆Топ 10 бубылд чата🏆\n\n' + dickos)

 


@dp.message_handler(commands=["globaldick"])
async def send_global_top(message: types.Message):


    arango_client = ArangoClient(hosts='https://arango.vdk2ch.ru') 
    pipisa_db     = arango_client.db('pipisa', username='root', password='stolendick527') 
    dicks_collection = pipisa_db.collection('dicks') 

    try:
        dicks = dicks_collection.all( ) 
        dicks = [d for d in dicks]
    except Exception as e: 
        print('ошибка DB в /glovaldick')
        print(e)

    top_dicks  = sorted(dicks, key=lambda dick: dick['dick_size'], reverse=True)
    
    dick_limit = min(len(top_dicks), 10)
    top_dicks  = top_dicks[:dick_limit]
  
    dickos = ''
    emo    = ['🏆','🚀','💫','🍆','🍌','🐍','🐎','🌭','🌶','👌']

    if len(top_dicks) == 0:
        await bot.send_message(message.chat.id, '🍆 Никто ничего не нарастил! 🍌')
    else:
        for i in range(len(top_dicks)): 
            dickos += f'     {emo[i]} {i+1}. {top_dicks[i]["user_fullname"]}: {top_dicks[i]["dick_size"]}см\n'
            i += 1

        await bot.send_message(message.chat.id, '🏆Топ 10 пипис в мире🏆\n\n' + dickos)