import discord
import discord.app_commands
import os
from keep_alive import keep_alive

client = discord.Client(intents=discord.Intents.default())
tree = discord.app_commands.CommandTree(client)

my_secret = os.environ['DISCORD_TOKEN']
GUILD_ID = os.environ['GUILD_ID']
guild = discord.Object(GUILD_ID)


class Panel(discord.ui.View):

  def __init__(self, game, time, host, timeout=None):
    super().__init__(timeout=None)
    self.game = game
    self.time = time
    self.host = host
    self.value = None
    self.userlist = [host]

  def setMessage(self, status):
    return f"募集要項:{self.game}\n開始時刻:{self.time}\nステータス:{status}\nメンバー:" + ",".join(
      self.userlist)

  @discord.ui.button(label="参加する",
                     style=discord.ButtonStyle.success,
                     custom_id="join")
  async def join(self, interaction: discord.Interaction,
                 button: discord.ui.Button):
    if (interaction.user.name in self.userlist):
      await interaction.response.edit_message(
        content=self.setMessage(f"{interaction.user.name}さんは既に参加しています。"))
    else:
      self.userlist.append(interaction.user.name)
      await interaction.response.edit_message(
        content=self.setMessage(f"{interaction.user.name}さんが参加しました。"))

  @discord.ui.button(label="キャンセル",
                     style=discord.ButtonStyle.grey,
                     custom_id="cancel")
  async def cancel(self, interaction: discord.Interaction,
                   button: discord.ui.Button):
    if (interaction.user.name == self.host):
      await interaction.response.edit_message(
        content=self.setMessage(f"ホストは参加をキャンセルできません。募集を終了する場合は削除を押してください。")
      )
      return
    if (interaction.user.name not in self.userlist):
      await interaction.response.edit_message(
        content=self.setMessage(f"{interaction.user.name}さんは参加していません。"))
    else:
      self.userlist.remove(interaction.user.name)
      await interaction.response.edit_message(
        content=self.setMessage(f"{interaction.user.name}さんがキャンセルしました。"))

  @discord.ui.button(label="メンバー確定",
                     style=discord.ButtonStyle.blurple,
                     custom_id="deci")
  async def deci(self, interaction: discord.Interaction,
                 button: discord.ui.Button):
    if (self.host == interaction.user.name):
      self.clear_items()
      await interaction.response.edit_message(
        content=self.setMessage(f"**メンバーが確定しました。**"), view=self)
      button.disabled = True
      self.stop()
    else:
      await interaction.response.edit_message(
        content=self.setMessage(f"募集を確定させられられるのはホストのみです。"))

  @discord.ui.button(label="削除",
                     style=discord.ButtonStyle.danger,
                     custom_id="quit")
  async def quit(self, interaction: discord.Interaction,
                 button: discord.ui.Button):
    if (self.host == interaction.user.name):
      self.clear_items()
      await interaction.message.delete()
      self.stop()
    else:
      await interaction.response.edit_message(
        content=self.setMessage(f"削除出来るのはホストのみです。"))


#募集ボタン作成
@tree.command(guild=guild, name="募集", description="人を募集する時に使用")
@discord.app_commands.describe(募集要項="募集する内容", 時間="開始時間を記入")
async def recruit(ctx: discord.Interaction, 募集要項: str, 時間: str):
  view = Panel(募集要項, 時間, ctx.user.name)
  await ctx.response.send_message(
    f" 募集要項:{募集要項}\n開始時刻:{時間}\nステータス:募集が開始されました\nメンバー:" + ctx.user.name,
    view=view)
  view.message = await ctx.original_response()


#Bot起動
@client.event
async def on_ready():
  print("ready...")
  await tree.sync(guild=guild)
  print("sync commands...")

keep_alive()
client.run(my_secret)
