import disnake
from disnake import TextInputStyle
import helpers
import json
import embed_factory
class LLModal(disnake.ui.Modal):
    def __init__(self,cp,pike=0,archer=0):
        components = [
            disnake.ui.TextInput(
                label="Enter CP Rank if number below is wrong",
                placeholder="Last CP was: {cp}".format(cp=cp),
                custom_id="cp",
                style=TextInputStyle.short,
                max_length=5,
                required=False,
                value = cp,
            ),
            disnake.ui.TextInput(
                label="Villa ID's seperate with space",
                placeholder="1234 4352 54234 ...etc",
                custom_id="villa_ids",
                style=TextInputStyle.short,
            ),
            disnake.ui.TextInput(
                label="How many Archers?",
                placeholder="200",
                custom_id="archers",
                value=pike,
                style=TextInputStyle.short,
            ),
            disnake.ui.TextInput(
                label="How many Pikes?",
                placeholder="300",
                custom_id="pikes",
                value=archer,
                style=TextInputStyle.short,
            ),
        ]
        super().__init__(
            title="Liege Lord Request Form",
            custom_id="submit_ll",
            components=components
        )

    async def callback(self,inter: disnake.ModalInteraction):
        await inter.response.defer(ephemeral=True)
        playerCP = inter.text_values['cp']
        prefArchers = inter.text_values['archers']
        prefPikes = inter.text_values['pikes']
        print("{player} is cp {cp} and input: {villaids}".format(player=inter.author.display_name,cp=playerCP,villaids=inter.text_values['villa_ids']))
        helpers.sql_set("INSERT INTO user(dID,name,cp,gID,prefArchers,prefPikes) VALUES(?,?,?,?,?,?) ON CONFLICT(dID) DO UPDATE SET cp = excluded.cp,prefArchers = excluded.prefArchers,prefPikes = excluded.prefPikes",(inter.author.id,inter.author.display_name,playerCP,inter.guild_id,prefArchers,prefPikes))
        result = json.loads(helpers.sql_get("SELECT lldata FROM guild WHERE gID = {gID}".format(gID = inter.guild.id))[0][0])

        if 'll' not in result.keys(): 
            await inter.response.send_message(content="Failed, no thread open", ephemeral=True) 
            return
        thread = inter.guild.get_channel_or_thread(result['ll'][1])

        if ',' in inter.text_values['villa_ids']:
            villa_ids = [villa for villa in inter.text_values['villa_ids'].split(',')]
        else:
            villa_ids = [villa for villa in inter.text_values['villa_ids'].split()]
        if len(villa_ids):
            for villa in villa_ids:
                button_done = disnake.ui.Button(emoji='✅',custom_id='llcheck')
                #button_done.callback = sbComponents.ll_button_callback
                embed = disnake.Embed(title="LL Request - {id} from {name} CP: {cp}".format(id=villa,cp=playerCP,name=inter.author.display_name))
                embed.description = "{name} is looking for a LL for {id}, if you fulfill this request, or have gotten a LL click the ✅ below to remove it from the list".format(name=inter.author.display_name,id=villa)
                embed.add_field(name="Archers",value=prefArchers,inline=True)
                embed.add_field(name="Pikes",value=prefPikes,inline=True)
                view = disnake.ui.View()
                view.add_item(button_done)
                msg = await thread.send(embed=embed,view=view)
                helpers.sql_set("INSERT INTO llrequests(parentID,villaID,ownerID,ownerCP,fulfilled,messageID,displayName) VALUES(?,?,?,?,?,?,?)",(thread.id,villa,inter.author.id,playerCP,0,msg.id,inter.author.display_name))
        channel = inter.guild.get_channel_or_thread(result['ll'][0])
        message = await channel.fetch_message(result['ll'][1])
        await message.edit(embed=embed_factory.lfll(result['ll'][1]))
        await channel.send(content="Request has been added!",delete_after=30)
        await inter.followup.send(content="Done! 💖 Should be listed here: <#{id}>".format(id=channel.id))
        return