using System;
using System.Reflection;
using System.Threading.Tasks;
using Discord;
using Discord.Commands;
using Discord.WebSocket;
using Microsoft.Extensions.DependencyInjection;
using Discord.Net.Providers.WS4Net;
using System.IO;

namespace Terrabot
{
    class Program
    {
        private readonly DiscordSocketClient client;
        private readonly CommandService commands = new CommandService();
        private IServiceProvider services;
        int jokelvl = 0;
        // Program entry point
        static void Main(string[] args)
        {
           new Program().AsyncMain().GetAwaiter().GetResult();
        }
        private Program()
        {
            client = new DiscordSocketClient(new DiscordSocketConfig
            {
                LogLevel = LogSeverity.Info,
                WebSocketProvider = WS4NetProvider.Instance
            });
        }
        private async Task AsyncMain()
        {
            // Subscribe the logging handler.
            client.Log += Logger;
            commands.Log += Logger;

            // Login and connect.
            string token = System.IO.File.ReadAllText(System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location) + "\\conf\\token.txt");
            await client.LoginAsync(TokenType.Bot, token);
            await client.StartAsync();

            await commands.AddModulesAsync(Assembly.GetEntryAssembly());
            ConfigureServices();
            // Wait infinitely so your bot actually stays connected.
            await Task.Delay(-1);
        }
        private IServiceProvider ConfigureServices()
        {
            client.MessageReceived += HandleCommand;
            client.MessageReceived += TextCommands;
            return services = new ServiceCollection()
                // Base
                .AddSingleton(client)
                .AddSingleton<CommandService>()
                .AddSingleton<AudioService>()
                .AddSingleton<TerraService>()
                // Add additional services here...
                .BuildServiceProvider();
        }
        public async Task HandleCommand(SocketMessage messageParam)
        {
            var message = messageParam as SocketUserMessage;
            if (message == null) return;
            string MessageLog = $"{DateTime.Now,-19} [    {message.Channel}] {message.Author} : {message.Content}";
            Console.WriteLine(MessageLog);
            File.AppendAllText(AppDomain.CurrentDomain.BaseDirectory + "log.txt", MessageLog + Environment.NewLine);
            int argPos = 0;
            if (!(message.HasCharPrefix('!', ref argPos) || message.HasMentionPrefix(client.CurrentUser, ref argPos))) return;
            var context = new CommandContext(client, message);
            var result = await commands.ExecuteAsync(context, argPos, services);
        }
        public async Task TextCommands(SocketMessage messageParam)
        {
            var message = messageParam as SocketUserMessage;
            if (message == null) { return; }
            if (message.Author.IsBot) { return; }
            if (message.ToString().Equals("Terrabot, A man fell out of a plane."))
            {
                jokelvl = 1;
                await message.Channel.SendMessageAsync("Oh, that's bad.");
                return;
            }
            if (message.ToString().Contains("good"))
            {
                if (jokelvl.Equals(1))
                {
                    await message.Channel.SendMessageAsync("Oh, that's good.");
                    return;
                }
            }
            if (message.ToString().Contains("bad"))
            {
                if (jokelvl.Equals(1))
                {
                    await message.Channel.SendMessageAsync("Oh, that's bad.");
                    return;
                }
            }
            if (message.ToString().Equals("No, that's bad, he missed the haystack."))
            {
                if (jokelvl.Equals(1))
                {
                    jokelvl = 0;
                    return;
                }
            }
        }
        private static Task Logger(LogMessage lmsg)
        {
            var cc = Console.ForegroundColor;
            switch (lmsg.Severity)
            {
                case LogSeverity.Critical:
                case LogSeverity.Error:
                    Console.ForegroundColor = ConsoleColor.Red;
                    break;
                case LogSeverity.Warning:
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    break;
                case LogSeverity.Info:
                    Console.ForegroundColor = ConsoleColor.White;
                    break;
                case LogSeverity.Verbose:
                case LogSeverity.Debug:
                    Console.ForegroundColor = ConsoleColor.DarkGray;
                    break;
            }
            string Log = $"{DateTime.Now,-19} [{lmsg.Severity,8}] {lmsg.Source}: {lmsg.Message}: {lmsg.Exception}";
            Console.WriteLine(Log);
            try
            {
                using (StreamWriter LogFile = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "log.txt", true))
                {
                    LogFile.WriteLine(Log + Environment.NewLine);
                }
            }
            catch (System.IO.IOException) { }
            Console.ForegroundColor = cc;
            return Task.CompletedTask;
        }
    } }