import discord
import requests
import asyncio
import aiohttp
import json
import calendar
import time
from discord.ext import commands, tasks
from discord.commands import slash_command
from mailtm import Email

with open('tempmail.json', 'r', encoding='utf-8') as f:
    tempmail = f.readlines()

class tempmail(commands.Cog):
    def __init__(self, bot: discord.Bot):
        self.bot = bot

    @commands.Cog.listener()
    async def on_ready(self):
        self.bot.add_view(setupview(self.bot, self.listener))

    def listener(self, message):
        with open('tempmail.json', 'r', encoding='utf-8') as f:
            data = json.load(f)
        if message['address'] in data:
            channel = self.bot.get_channel(data[message['to']]['channel_id'])
            embed = discord.Embed(title="New email", description=f"Subject: {message['subject']}\nContent: {message['text'] if message['text'] else message['html']}", color=discord.Colour.embed_background())
            channel.send(embed=embed)


    @slash_command(name="setup_panel", description="Setup temp mail panel", guild_ids=[1186445469442920508])
    async def setup_panel(self, ctx: commands.Context):
         embed = discord.Embed(title="Setup Panel", description="Setup panel created", color=discord.Colour.embed_background())
         await ctx.channel.send(embed=embed, view=setupview(self.bot, self.listener))
         await ctx.respond(embed=embed, ephemeral=True)

def setup(bot: discord.Bot):
    bot.add_cog(tempmail(bot))

class setupview(discord.ui.View):
    def __init__(self, bot, listener):
        super().__init__(timeout=None)
        self.bot = bot
        self.listener = listener

    @discord.ui.button(label="Create temp mail", style=discord.ButtonStyle.primary, emoji="⭐", custom_id="keks", row=2)
    async def button_callback1(self, button, interaction):
        current_GMT = time.gmtime()
        time_stamp = calendar.timegm(current_GMT)
        self.email = Email()
        self.email.register()
        self.email.start(self.listener)
        category = self.bot.get_channel(1189704833607938060)
        channel = await category.create_text_channel(self.email.address)
        with open('tempmail.json', 'r', encoding='utf-8') as f:
            data = json.load(f)
        data[self.email.address] = {
            "address": self.email.address,
            "channel_id": channel.id,
            "time_created": time_stamp
        }
        with open('tempmail.json', 'w', encoding='utf-8') as f:
            json.dump(data, f, indent=4)
        embed = discord.Embed(title="Temp mail created", description=f"Your temp mail is {self.email.address}", color=discord.Colour.embed_background())
        await interaction.response.send_message(embed=embed, ephemeral=True)
        await channel.send(embed=embed)