from plasmaBot.plugin import PBPlugin, PBPluginMeta, Response, PBPluginConfig
import discord
import asyncio

from SQLiteHelper import SQLiteHelper as sq

from plasmaBot import exceptions

import logging
log = logging.getLogger('discord')


# Database Default Classes
class dbt_moderation_settings(object):
    def __init__(self):
        self.columns = ["SERVER_ID", "PRESERVE_OVERRIDES", "SOFT_MUTE"]
        self.datatypes = ["TEXT PRIMARY KEY NOT NULL", "TEXT", "TEXT"]
        self.seed = []

class dbt_moderation_roles(object):
    def __init__(self):
        self.columns = ["SERVER_ID", "ROLE_MUTE", "ROLE_DEAFEN"]
        self.datatypes = ["TEXT PRIMARY KEY NOT NULL", "TEXT", "TEXT"]
        self.seed = []


class Moderation(PBPlugin):
    name = 'Moderation'
    globality = 'all'
    help_exclude = True

    def __init__(self, plasmaBot):
        super().__init__(plasmaBot)

        self.toggles = ['preserve_overrides', 'soft_mute']

        self.pl_config = PBPluginConfig(plasmaBot, 'moderation.ini', 'MODERATION', {'Files':[['moderation_db_location', 'The location of the moderation database', 'data/moderation']]})

        self.moderation_db = sq.Connect(self.pl_config.moderation_db_location)

        if not self.moderation_db.table('s_preferences').tableExists():
            initiation_glob = dbt_moderation_settings()
            self.moderation_db.table('s_preferences').init(initiation_glob)

        if not self.moderation_db.table('s_roles').tableExists():
            initiation_glob = dbt_moderation_roles()
            self.moderation_db.table('s_roles').init(initiation_glob)


    async def toggle(self, server, key):

        #Get Server Data

        moderation_settings = self.moderation_db.table('s_preferences').select("SERVER_ID", "PRESERVE_OVERRIDES", "SOFT_MUTE").where("SERVER_ID").equals(server.id).execute()

        SERVER_ID = None
        PRESERVE_OVERRIDES = None
        SOFT_MUTE = None

        for server_instance in moderation_settings:
            SERVER_ID = server_instance[0]
            PRESERVE_OVERRIDES = server_instance[1]
            SOFT_MUTE = server_instance[2]

        try:
            server_id = int(SERVER_ID)
        except:
            server_id = None

        if isinstance( server_id, int ):
            if not (PRESERVE_OVERRIDES == 'true' or PRESERVE_OVERRIDES == 'false'):
                self.moderation_db.table('s_preferences').update("PRESERVE_OVERRIDES").setTo('true').where("SERVER_ID").equals(server.id).execute()

            if not (SOFT_MUTE == 'true' or SOFT_MUTE == 'false'):
                self.moderation_db.table('s_preferences').update("SOFT_MUTE").setTo('false').where("SERVER_ID").equals(server.id).execute()
        else:
            self.moderation_db.table('s_preferences').insert(server.id, "true", "false").into("SERVER_ID", "PRESERVE_OVERRIDES", "SOFT_MUTE")

        #Handle Keys

        if key == "preserve_overrides":

            #Invert values and save in db

            if PRESERVE_OVERRIDES == 'true':
                PRESERVE_OVERRIDES = 'false'
            elif PRESERVE_OVERRIDES == 'false':
                PRESERVE_OVERRIDES = 'true'
            else:
                PRESERVE_OVERRIDES = None

            if PRESERVE_OVERRIDES == None:
                PRESERVE_OVERRIDES = 'true'
            else:
                self.moderation_db.table('s_preferences').update("PRESERVE_OVERRIDES").setTo(PRESERVE_OVERRIDES).where("SERVER_ID").equals(server.id).execute()

            return ['SUCCESS', PRESERVE_OVERRIDES]

        elif key == 'soft_mute':

            #Invert values and sasve in db

            if SOFT_MUTE == 'true':
                SOFT_MUTE = 'false'
            elif SOFT_MUTE == 'false':
                SOFT_MUTE = 'true'
            else:
                SOFT_MUTE = None

            if SOFT_MUTE == None:
                SOFT_MUTE = 'false'
            else:
                self.moderation_db.table('s_preferences').update("SOFT_MUTE").setTo(SOFT_MUTE).where("SERVER_ID").equals(server.id).execute()

            return ['SUCCESS', SOFT_MUTE]

        else:
            return 'ERROR'


    async def get_key(self, server, key):

        #Get Server Data

        moderation_settings = self.moderation_db.table('s_preferences').select("SERVER_ID", "PRESERVE_OVERRIDES", "SOFT_MUTE").where("SERVER_ID").equals(server.id).execute()

        SERVER_ID = None
        PRESERVE_OVERRIDES = None
        SOFT_MUTE = None

        for server_instance in moderation_settings:
            SERVER_ID = server_instance[0]
            PRESERVE_OVERRIDES = server_instance[1]
            SOFT_MUTE = server_instance[2]

        try:
            server_id = int(SERVER_ID)
        except:
            server_id = None

        if isinstance( server_id, int ):
            if not (PRESERVE_OVERRIDES == 'true' or PRESERVE_OVERRIDES == 'false'):
                self.moderation_db.table('s_preferences').update("PRESERVE_OVERRIDES").setTo('true').where("SERVER_ID").equals(server.id).execute()

            if not (SOFT_MUTE == 'true' or SOFT_MUTE == 'false'):
                self.moderation_db.table('s_preferences').update("SOFT_MUTE").setTo('false').where("SERVER_ID").equals(server.id).execute()
        else:
            self.moderation_db.table('s_preferences').insert(server.id, "true", "false").into("SERVER_ID", "PRESERVE_OVERRIDES", "SOFT_MUTE")

        #Pull Key

        if key == "preserve_overrides":

            if PRESERVE_OVERRIDES == 'true':
                PRESERVE_OVERRIDES = True
            elif PRESERVE_OVERRIDES == 'false':
                PRESERVE_OVERRIDES = False
            else:
                PRESERVE_OVERRIDES = True

            return PRESERVE_OVERRIDES


        elif key == "soft_mute":

            if SOFT_MUTE == 'true':
                SOFT_MUTE = True
            elif SOFT_MUTE == 'false':
                SOFT_MUTE = False
            else:
                SOFT_MUTE = False

            return SOFT_MUTE

        else:
            return 'ERROR'


    async def get_roles(self, server):
        server_roles = server.roles


        self_member = server.get_member(self.bot.user.id)
        top_role = self_member.top_role
        role_position = top_role.position

        permissions = server.get_channel(server.id).permissions_for(self_member)
        manage_roles = permissions.manage_roles

        m_overwrite = discord.PermissionOverwrite()
        m_overwrite.send_messages = False
        d_overwrite = discord.Per
missionOverwrite()
        d_overwrite.send_messages = False
        d_overwrite.read_messages = False

        if not manage_roles:
            return [None, None]
        else:
            mute_role = None
            defen_role = None

            server_role_entry = self.moderation_db.table('s_roles').select("ROLE_MUTE", "ROLE_DEAFEN").where("SERVER_ID").equals(server.id).execute()

            everyone_permissions = None
            role_mute = 'DNE'
            role_deafen = 'DNE'
            role_return = [None, None, manage_roles]

            for server_entry in server_role_entry:
                role_mute = server_entry[0]
                role_deafen = server_entry[1]

            if role_mute and role_deafen:
                for role in server.roles:
                    if role.position == 0:
                        everyone_permissions = role.permissions

                    if role.id == role_mute:
                        role_return[0] = role

                    if role.id == role_deafen:
                        role_return[1] = role


            if role_return[0] and role_return[1]:
                return role_return

            if role_mute == 'DNE' and role_deafen == 'DNE':
                assign_db = True
            else:
                assign_db = False

            if role_return[0] == None:
                mute_perms = everyone_permissions
                mute_perms.send_messages = False

                role_return[0] = await self.bot.create_role(server, name='PB-Muted', mentionable=False, permissions=mute_perms)
                await self.bot.move_role(server, role_return[0], role_position)

                if not assign_db:
    