using DSharpPlus.Entities;
using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Channels;
using System.Threading.Tasks;

namespace IFE_0._3
{

    //Message Controller
    internal class Messanger
    {
        //Primary Game Channel
        DiscordChannel gameChannel;
        //These are the lists that hold "transient" messages. Messages that are to be delted
        List<ulong?> serverCleanupList = new List<ulong?>();
        List<ulong?> cleanupList = new List<ulong?>();

        public void setGameChannel(DiscordChannel GC)
        {
            gameChannel = GC;
        }

        //Sends message with image to either a player or the server
        public async Task sendMessage(string text, string imageName, bool transient = false, Player player = null)
        {
            DiscordChannel channel = gameChannel;
            if (!(player is null))
            {
                channel = player.getChannel();
            }

            FileStream fs = ImageProcessor.getImage(imageName);
            var msg = new DiscordMessageBuilder().WithContent(text).AddFile(fs).SendAsync(channel);
            await msg;
            if (transient)
            {
                serverCleanupList.Add(msg.Result.Id);
            }
            fs.Close();
        }


        //Sends message to either a player or the server
        public async Task sendMessage(string text, bool transient = false, Player player = null)
        {
            DiscordChannel channel = gameChannel;
            if (!(player is null))
            {
                channel = player.getChannel();
            }

            var msg = new DiscordMessageBuilder().WithContent(text).SendAsync(gameChannel);
            await msg;
            if (transient)
            {
                serverCleanupList.Add(msg.Result.Id);
            }
        }

        //Sends a message with Buttons to either a player or server 
        public async Task sendMessage(string text, List<DiscordComponent> buttons, bool transient = false, Player player = null)
        {
            DiscordChannel channel = gameChannel;
            if (!(player is null))
            {
                channel = player.getChannel();
            }

            var msg = new DiscordMessageBuilder().WithContent(text).AddComponents(buttons).SendAsync(channel);
            await msg;
            if (transient)
            {
                cleanupList.Add(msg.Result.Id);
            }
        }

        //Cleanup Messages in player chat. 
        //Todo: Replace with within this class
        public static void cleanUpAll(List<Player> x)
        {
            foreach (Player p in x)
            {
                p.cleanUpMessages();
            }
        }
        
        public async void cleanUpMessages(Player player)
        {
            foreach (ulong x in cleanupList)
            {
                //Gotta Fix This
                var y = await player.getChannel().GetMessageAsync(x);
                player.getChannel().DeleteMessageAsync(y);
            }
        }

        //NOTE: THe next few methods are basically text dumps. 
        //In the future most of these should be gotten from a text file. 

        public void sendEnrolmentMessage()
        {
            sendMessage("The Impossible Flux Engine allowed multiversal travel a millenia ago. " +
                "Wars, trade routes, alliances and eventually unity accross the infinte expanse of every reality" +
                "Then one day, Silence. One by one, all communications froms certain universes stopped. Any expiditions into these quite universes resulted in nothing but a lost ship" +
                "More and more of these went dark and trade routes collapsed, and no one knew why. " +
                "A ship semi functioning ship drifts in a dump attracts a small number of despereate traverls to crew it " +
                "Boarding the ship, the members hear a soothing voice, calling for them to, beconning them something, something to fight and preserver what's coming \n \n " +
                "Follow the 3 beacons, listen to the coordinates, muffled however as they may be and beware of those that would rather embrace the nothingness.", "startUniverse.gif");

            sendMessage("Enrolment has started. Type /enrol. When you everyone's enrolled, type /ready", true);
        }

        public void sendCaptainVote()
        {
            sendMessage("The drifters use what skills they have to get the ship ready, finding an assortment of equipment in the process. " +
    "Firstly, as captain must be decided upon, who can act as a tie breaker in votes, and who will hold onto the on weapon found. Cast your votes" +
    "(note, captain will not hear the call of the abyss)");
        }

        public void sendNonAbyss(Player player)
        {
            sendMessage("These filth do not know what you do. They have not experienced the utter black as you have" +
                        "These fools press their ears up against their windows and mistake the last whimper of the past as a guiding light" +
                        "You will let this existence end. Help me snuff it out so we can begin this cursed existance anew" +
                        "Along with the locations of their, so called, 'haven' universes, you will be relayed the coordinates of universes under my domain", false, player);
        }
         public void sendAbyss(Player player)
        {
            sendMessage("Everything must end. No matter for far our technology and progress goes that seems to be a constant" +
                        "At the end of it all, if there were ever to be a fight worth fighting for, why not the fight to be alive, to continue. " +
                        "No matter how futile, or pointless it is, why not push for this, the only thing left to push for" +
                        "Listen to the ripples of hope that flow through the cosmic ether and plunge forward.", false, player);
        }
        
        public void sendPostion(Player player, position pos)
        {
            string message = "";
            switch (pos)
            {
                case position.pilot:
                    message = "Your captain is trusting you to pilot the ship. Congrats. Try not to fly into anything too wacky \n" +
                        "You can activate your abiilty to evade universes that would otherwise kill you. How do you evade that shit? I don't fucking know";
                    break;
                case position.security:
                    message = "Your captain has given you the responsibility of the security officer. Go and waterboard some cunts \n" +
                        "You'll be able to make them tell you what they voted. Or whatever will make you stop hitting them";
                    break;
                case position.captain:
                    message = "Congrats, you've been voted the captain. El Jefe. Chief \n" +
                        "You've been handed a gun to deal with any disobediance. In the event of a tie, the vote will be defered to you";
                    break;
                case position.science:
                    message = "Look sharp, 4 eyes. You've been assigned as the science officer. Go do some...ahhh...science \n " +
                        "You have the ability to scan to see what other peoples clues are. Useful to see if anyone's bullshiting.";
                    break;
                case position.engineering:
                    message = "The crew wants you to know that they love you, and you're a beautiful human being, but you're being stationed as the engineer, deep deep away from everyone. They'll stay in touch on the com channels though \n" +
                        "You can activate your ability to get a random digit from the target";
                    break;
            }
            sendMessage(message, false, player);
        }

        public void sendNominationMessage()
        {
            sendMessage("Nominations are now open. To nominate type xxxx with the x's representing the coordinates", true);
        } 

        public async Task sendJump()
        {
            sendMessage("All votes have been processed...");
            await Task.Delay(2000);
            sendMessage("The IFD starts spinning...");
            await Task.Delay(2000);
            sendMessage("The ship jumps...", "universes2Jump.gif");
            await (Task.Delay(4000));
        }

        public void sendJettisonVote()
        {
            sendMessage("As feel the rotational inertia piter out, it's not met with the same feeling of existential inertia that you normally feel+ " +
            " You feel an emptiness start take hold, sucking you in and strectching you out, making you feel ever thinner and thinner" +
            "Before you fade out of existence you somehow know your last hope is to saccrifice someone to the void. All that matters is deciding who"
            , "universesAbyss.gif");
        }

        public void sendPostJump()
        {
            sendMessage("The jump goes smoothly. Except for a little bit of sickness you feel more or less Ok." +
            " The crew checks on each other via the com system and " +
            "begin the post jump maintanance \n \n \n" +
            "(Additional universes have been calimed)", "universes2.gif");
        }
    }
}