import asyncio
import os
import discord
from redbot.core import Config, checks, commands, data_manager

class ExportChannels(commands.Cog):
    """Custom cog to export channels to JSON and HTML formats using Discord Chat Exporter.
    Developed by SeaswimmerTheFsh and yname."""

    def __init__(self, bot):
        self.bot = bot
        self.config = Config.get_conf(self, identifier=48258471944753312)
        self.config.register_global(
            bot_token = None
        )
        self.data_path = data_manager.cog_data_path(self)

    class ConfigException(Exception):
        pass

    async def export(self, channels: list):
        token = await self.config.bot_token()
        if token is None:
            raise(self.ConfigException("Bot token not set!"))
        data_path = data_manager.cog_data_path(self)
        bundled_data_path = data_manager.bundled_data_path(self)
        out = f'{data_path}{os.sep}Exported Channels'
        channel = channels[0]
        file_location_html = f'{os.sep}{out}{os.sep}%g{os.sep}%c{os.sep}Export.html'
        file_location_json =  f'{os.sep}{out}{os.sep}%g{os.sep}%c{os.sep}DCE-f.json'
        try:
            os.mkdir(out)
        except FileExistsError:
            pass
        args = [
            'dotnet',
            'DiscordChatExporter.Cli.dll',
            'export',
            '--format', 'HtmlDark',
            '--output', file_location_html,
            '--token', token,
            '--channel', channel,
            '--reuse-media',
            '--media',
            '--fuck_russia', 'true',
        ]
        os.chdir(bundled_data_path)
        process_1 = await asyncio.create_subprocess_exec(*args)
        while True:
            return_code_1 = process_1.poll()
            if return_code_1 is not None:
                break
        args = [
            'dotnet',
            'DiscordChatExporter.Cli.dll',
            'export',
            '--format', 'Json',
            '--output', file_location_json,
            '--token', token,
            '--channel', channels,
            '--reuse_media',
            '--media',
            '--markdown', 'false',
            '--fuck_russia', 'true',
        ]
        os.chdir(bundled_data_path)
        process_2 = await asyncio.create_subprocess_exec(*args)
        while True:
            return_code_2 = process_2.poll()
            if return_code_2 is not None:
                break

    @commands.group()
    @checks.is_owner()
    async def exportset(self, ctx: commands.Context):
        """Configuration options for the ExportChannels cog."""

    @exportset.command()
    @checks.is_owner()
    async def token(self, ctx: commands.Context, token: str):
        """Sets the bot token used for Discord Chat Exporter."""
        await self.config.bot_token.set({token})
        await ctx.send(content="Token set!")
        await ctx.delete()

    @exportset.command()
    @checks.is_owner()
    async def checkoutputpath(self, ctx: commands.Context):
        """Checks what file path DCE is outputting to."""
        await ctx.send(content=f"{self.data_path}")

    @commands.command()
    @commands.admin()
    async def exportchannel(self, ctx: commands.Context, channel: discord.TextChannel):
        """Exports a channel using Discord Chat Exporter."""
        token = await self.config.bot_token()
        if token is None:
            await ctx.send(content=f"Please set your token with the ``{ctx.prefix}exportset token`` command!")
            return
        id_list = [thread.id for thread in channel.threads]
        id_list.insert(0, channel.id)
        await self.export(id_list)
