from sys import path, platform
#if platform == 'linux':
#    path.append('/home/ubuntu/.local/lib/python3.8/site-packages/')

from telegram import Update, MessageEntity
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackQueryHandler, InlineQueryHandler
from json import dumps, loads
from uuid import uuid4
from os import remove
from var import bot, bannedids, pinggroups
import unnecesarry as cmd_unnecesarry
# import ocr as cmd_ocr
import official as cmd_official
import handlers
from flask import Flask, request

class moderation:
    @staticmethod
    def ban(update: Update, context):
        if update.message.from_user.id in bannedids:
            return
        if update.message.from_user.id != 1341877177:
            update.message.reply_text('You cant use dis XD')
            return
        if update.message.reply_to_message.from_user.id in bannedids:
            update.message.reply_text('User is already banned.')
            return
        bannedids.append(update.message.reply_to_message.from_user.id)
        with open('banned.json', 'w') as f:
            f.write(dumps(bannedids))
        update.message.reply_text(f'{update.message.reply_to_message.from_user.first_name} '
                                  f'({update.message.reply_to_message.from_user.id}) is banned.')

    @staticmethod
    def unban(update: Update, context):
        if update.message.from_user.id in bannedids:
            return
        if update.message.from_user.id != 1341877177:
            update.message.reply_text('You cant use dis XD')
            return
        if update.message.reply_to_message.from_user.id not in bannedids:
            update.message.reply_text('User is not banned.')
            return
        bannedids.remove(update.message.reply_to_message.from_user.id)
        with open('banned.json', 'w') as f:
            f.write(dumps(bannedids))
        update.message.reply_text(f'{update.message.reply_to_message.from_user.first_name} '
                                  f'({update.message.reply_to_message.from_user.id}) is unbanned.')

    @staticmethod
    def getchatid(update: Update, context):
        update.message.reply_text(update.message.chat.id)

    @staticmethod
    def makepinggroup(update: Update, context):
        if update.message.from_user.id in bannedids:
            return
        if str(update.message.chat.id) not in pinggroups.keys():
            pinggroups[str(update.message.chat_id)] = {}
        pinggroups[str(update.message.chat.id)][update.message.text.split(' ')[1]] = []
        with open('pinggroups.json', 'w') as f:
            f.write(dumps(pinggroups, indent=2))
        update.message.reply_text(f'Made ping group \'{update.message.text.split(" ")[1]}\' ')

    @staticmethod
    def addusertopinggroup(update: Update, context):
        if update.message.from_user.id in bannedids:
            return
        if update.message.text.split(' ')[1] in pinggroups[str(update.message.chat_id)].keys():
            pinggroups[str(update.message.chat.id)][update.message.text.split(' ')[1]].append \
                (update.message.reply_to_message.from_user.id)
            with open('pinggroups.json', 'w') as f:
                f.write(dumps(pinggroups, indent=2))
            update.message.reply_text(f'User added to group \'{update.message.text.split(" ")[1]}\'')

    @staticmethod
    def ping(update: Update, context):
        if update.message.from_user.id in bannedids:
            return
        text = f'Pinged {update.message.text.split(" ")[1]}\u2060'
        count = len(text)
        entities = []
        for i in pinggroups[str(update.message.chat.id)][update.message.text.split(' ')[1]]:
            text += '\u2060'
            entities.append(MessageEntity('text_mention', count, 1, user={'id': i}))
            count += 1
        update.message.reply_text(text, entities=entities)

    @staticmethod
    def getpinggroups(update: Update, context):
        if update.message.from_user.id != 1341877177:
            update.message.reply_text('You cant use dis XD')
            return
        if str(update.message.chat.id) in pinggroups.keys():
            _id = str(uuid4())
            with open(_id + '.txt', 'w') as f:
                f.write(dumps(pinggroups[str(update.message.chat.id)], indent=2))
            update.message.reply_document(open(_id + '.txt'),
                                          caption='May the pings be with you.')
            remove(_id + '.txt')
        else:
            update.message.reply_text('Man, theres no groups in this group. Pathetic.')

    @staticmethod
    def delmessage(update: Update, context):
        if update.message.from_user.id in bannedids:
            return
        if update.message.from_user.id != 1341877177:
            update.message.reply_text('You cant use dis XD')
            return
        if update.message.reply_to_message.from_user.username == 'SpaceTheBot':
            update.message.reply_to_message.delete()
            return
        update.message.reply_text('Must reply to spacebot\'s message')

    @staticmethod
    def stealDisMansID(update: Update, context):
        if update.message.from_user.id in bannedids:
            return
        if update.message.from_user.id != 1341877177:
            update.message.reply_text('You cant use dis XD')
            return
        if update.message.reply_to_message == None:
            update.message.reply_text('U forgot to reply to the guy man')
            return
        update.message.reply_text(str(update.message.reply_to_message.from_user.id))

    @staticmethod
    def ghostPingIDS(update: Update, context):
        if update.message.from_user.id in bannedids:
            return
        if update.message.from_user.id != 1341877177:
            update.message.reply_text('You cant use dis XD')
            return
        ids = [int(i) for i in update.message.text.split(' ')[1:]]
        entities = []
        for i in range(len(ids)):
            entities.append(MessageEntity('text_mention', i, 1, user={'id': ids[i]}))
        update.message.reply_text('\u2060' * len(entities), entities=entities)

def start(update: Update, context):
    update.message.reply_text('Theres currently no /help command in this bot. Explore urself.')

def error(update: Update, context):
    print(f'update {update.to_dict()} caused error {context.error}')

updater = Updater(bot=bot)
dp = updater.dispatcher

dp.add_error_handler(error)
dp.add_handler(CommandHandler('start', start))

# OFFICIAL COMMANDS #
dp.add_handler(CommandHandler('to512pic', cmd_official.to512pxc))
dp.add_handler(CommandHandler('joke', cmd_official.joke))
dp.add_handler(CommandHandler('addjoke', cmd_official.joke_add))
dp.add_handler(CommandHandler('getjokes', cmd_official.jokes_))
dp.add_handler(CommandHandler('choose', cmd_official.choose))
dp.add_handler(CommandHandler('shuffle', cmd_official.shuffle))
dp.add_handler(CommandHandler('mathquiz', cmd_official.mathq))
dp.add_handler(CommandHandler('addtexts', cmd_official.addtexts))
dp.add_handler(CommandHandler('makelist', cmd_official.makelist))
dp.add_handler(CommandHandler('slip', cmd_official.slip))
# dp.add_handler(CommandHandler('ocr', cmd_ocr.cmd))

# UNNECESARRY COMMANDS #
dp.add_handler(CommandHandler('secrets', cmd_unnecesarry.h_secrets))
dp.add_handler(CommandHandler('fart', cmd_unnecesarry.farts.fart))
dp.add_handler(CommandHandler('monkefart', cmd_unnecesarry.farts.m_fart))
dp.add_handler(CommandHandler('pigfart', cmd_unnecesarry.farts.p_fart))
dp.add_handler(CommandHandler('cowfart', cmd_unnecesarry.farts.c_fart))
dp.add_handler(CommandHandler('astronaut', cmd_unnecesarry.memes.astronaut))
dp.add_handler(CommandHandler('board', cmd_unnecesarry.memes.board))
dp.add_handler(CommandHandler('blank', cmd_unnecesarry.memes.blank))
dp.add_handler(CommandHandler('xuehuapiaopiao', cmd_unnecesarry.xue))
dp.add_handler(CommandHandler('searchidword', cmd_unnecesarry.searchidword))
dp.add_handler(CommandHandler('defineidword', cmd_unnecesarry.defineidword))
dp.add_handler(CommandHandler('sqrt', cmd_unnecesarry.math_.sqrt))
dp.add_handler(CommandHandler('cbrt', cmd_unnecesarry.math_.cbrt))
dp.add_handler(CommandHandler('truth', cmd_unnecesarry.tod.truth))
dp.add_handler(CommandHandler('dare', cmd_unnecesarry.tod.dare))
dp.add_handler(CommandHandler('add_dare', cmd_unnecesarry.tod.dare_add))
dp.add_handler(CommandHandler('add_truth', cmd_unnecesarry.tod.truth_add))

# BETA COMMANDS #
dp.add_handler(CommandHandler('addpinggroup', moderation.makepinggroup))
dp.add_handler(CommandHandler('addusertopinggroup', moderation.addusertopinggroup))
dp.add_handler(CommandHandler('ping', moderation.ping))
dp.add_handler(CommandHandler('getpinggroups', moderation.getpinggroups))

# ONLY QUEBEH XD #
dp.add_handler(CommandHandler('banuser', moderation.ban))
dp.add_handler(CommandHandler('unbanuser', moderation.unban))
dp.add_handler(CommandHandler('delete', moderation.delmessage))
dp.add_handler(CommandHandler('stealDisMansID', moderation.stealDisMansID))
dp.add_handler(CommandHandler('ghostPingIDS', moderation.ghostPingIDS))
dp.add_handler(CommandHandler('chatid', moderation.getchatid, filters=Filters.chat_type.groups))

# OTHER HANDLERS #
dp.add_handler(CallbackQueryHandler(handlers.callback))
dp.add_handler(MessageHandler(Filters.text | Filters.photo, handlers.msghandler))
dp.add_handler(InlineQueryHandler(handlers.inlinequery))

print('\rBot init.')

app = Flask('spes')

@app.route('/')
def index():
    return 'real'

@app.route('/'+bot.token, methods=['POST'])
def real():
    dp.process_update(Update.de_json(loads(request.data.decode()), bot))
    return '', 200

